repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
unknown
date_merged
unknown
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Scripting/VisualBasicTest.Desktop/InteractiveSessionTests.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.Scripting.Test Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests Public Class InteractiveSessionTests Inherits TestBase ' TODO: port tests from C# 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.Scripting.Test Imports Microsoft.CodeAnalysis.VisualBasic Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.Scripting.UnitTests Public Class InteractiveSessionTests Inherits TestBase ' TODO: port tests from C# End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AddAccessibilityModifiersHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers { internal static class AddAccessibilityModifiersHelpers { public static void UpdateDeclaration( SyntaxEditor editor, ISymbol symbol, SyntaxNode declaration) { Contract.ThrowIfNull(symbol); var preferredAccessibility = GetPreferredAccessibility(symbol); // Check to see if we need to add or remove // If there's a modifier, then we need to remove it, otherwise no modifier, add it. editor.ReplaceNode( declaration, (currentDeclaration, _) => UpdateAccessibility(currentDeclaration, preferredAccessibility)); return; SyntaxNode UpdateAccessibility(SyntaxNode declaration, Accessibility preferredAccessibility) { var generator = editor.Generator; // If there was accessibility on the member, then remove it. If there was no accessibility, then add // the preferred accessibility for this member. return generator.GetAccessibility(declaration) == Accessibility.NotApplicable ? generator.WithAccessibility(declaration, preferredAccessibility) : generator.WithAccessibility(declaration, Accessibility.NotApplicable); } } private static Accessibility GetPreferredAccessibility(ISymbol symbol) { // If we have an overridden member, then if we're adding an accessibility modifier, use the // accessibility of the member we're overriding as both should be consistent here. if (symbol.GetOverriddenMember() is { DeclaredAccessibility: var accessibility }) return accessibility; // Default abstract members to be protected, and virtual members to be public. They can't be private as // that's not legal. And these are reasonable default values for them. if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol) { if (symbol.IsAbstract) return Accessibility.Protected; if (symbol.IsVirtual) return Accessibility.Public; } // Otherwise, default to whatever accessibility no-accessibility means for this member; return symbol.DeclaredAccessibility; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers { internal static class AddAccessibilityModifiersHelpers { public static void UpdateDeclaration( SyntaxEditor editor, ISymbol symbol, SyntaxNode declaration) { Contract.ThrowIfNull(symbol); var preferredAccessibility = GetPreferredAccessibility(symbol); // Check to see if we need to add or remove // If there's a modifier, then we need to remove it, otherwise no modifier, add it. editor.ReplaceNode( declaration, (currentDeclaration, _) => UpdateAccessibility(currentDeclaration, preferredAccessibility)); return; SyntaxNode UpdateAccessibility(SyntaxNode declaration, Accessibility preferredAccessibility) { var generator = editor.Generator; // If there was accessibility on the member, then remove it. If there was no accessibility, then add // the preferred accessibility for this member. return generator.GetAccessibility(declaration) == Accessibility.NotApplicable ? generator.WithAccessibility(declaration, preferredAccessibility) : generator.WithAccessibility(declaration, Accessibility.NotApplicable); } } private static Accessibility GetPreferredAccessibility(ISymbol symbol) { // If we have an overridden member, then if we're adding an accessibility modifier, use the // accessibility of the member we're overriding as both should be consistent here. if (symbol.GetOverriddenMember() is { DeclaredAccessibility: var accessibility }) return accessibility; // Default abstract members to be protected, and virtual members to be public. They can't be private as // that's not legal. And these are reasonable default values for them. if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol) { if (symbol.IsAbstract) return Accessibility.Protected; if (symbol.IsVirtual) return Accessibility.Public; } // Otherwise, default to whatever accessibility no-accessibility means for this member; return symbol.DeclaredAccessibility; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Test/MetadataAsSource/AbstractMetadataAsSourceTests.TestContext.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.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public abstract partial class AbstractMetadataAsSourceTests { public const string DefaultMetadataSource = "public class C {}"; public const string DefaultSymbolMetadataName = "C"; internal class TestContext : IDisposable { public readonly TestWorkspace Workspace; private readonly IMetadataAsSourceFileService _metadataAsSourceService; public static TestContext Create( string? projectLanguage = null, IEnumerable<string>? metadataSources = null, bool includeXmlDocComments = false, string? sourceWithSymbolReference = null, string? languageVersion = null, string? metadataLanguageVersion = null) { projectLanguage ??= LanguageNames.CSharp; metadataSources ??= SpecializedCollections.EmptyEnumerable<string>(); metadataSources = !metadataSources.Any() ? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource } : metadataSources; var workspace = CreateWorkspace( projectLanguage, metadataSources, includeXmlDocComments, sourceWithSymbolReference, languageVersion, metadataLanguageVersion); return new TestContext(workspace); } public TestContext(TestWorkspace workspace) { Workspace = workspace; _metadataAsSourceService = Workspace.GetService<IMetadataAsSourceFileService>(); } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public Project DefaultProject { get { return this.CurrentSolution.Projects.First(); } } public Task<MetadataAsSourceFile> GenerateSourceAsync(ISymbol symbol, Project? project = null, bool allowDecompilation = false) { project ??= this.DefaultProject; Contract.ThrowIfNull(symbol); // Generate and hold onto the result so it can be disposed of with this context return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); } public async Task<MetadataAsSourceFile> GenerateSourceAsync(string? symbolMetadataName = null, Project? project = null, bool allowDecompilation = false) { symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName; project ??= this.DefaultProject; // Get an ISymbol corresponding to the metadata name var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation); Contract.ThrowIfNull(symbol); if (allowDecompilation) { foreach (var reference in compilation.References) { if (AssemblyResolver.TestAccessor.ContainsInMemoryImage(reference)) { continue; } if (reference is PortableExecutableReference portableExecutable) { Assert.True(File.Exists(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' does not exist for reference '{portableExecutable.Display}'"); Assert.True(Path.IsPathRooted(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' is not a fully-qualified file name"); } else { Assert.True(File.Exists(reference.Display), $"'{reference.Display}' does not exist"); Assert.True(Path.IsPathRooted(reference.Display), $"'{reference.Display}' is not a fully-qualified file name"); } } } // Generate and hold onto the result so it can be disposed of with this context var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); return result; } public static void VerifyResult(MetadataAsSourceFile file, string expected) { var actual = File.ReadAllText(file.FilePath).Trim(); var actualSpan = file.IdentifierLocation.SourceSpan; // Compare exact texts and verify that the location returned is exactly that // indicated by expected MarkupTestFile.GetSpan(expected, out expected, out var expectedSpan); AssertEx.EqualOrDiff(expected, actual); Assert.Equal(expectedSpan.Start, actualSpan.Start); Assert.Equal(expectedSpan.End, actualSpan.End); } public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool allowDecompilation = false) { var result = await GenerateSourceAsync(symbolMetadataName, project, allowDecompilation); VerifyResult(result, expected); } public static void VerifyDocumentReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.Same(a.FilePath, b.FilePath); public static void VerifyDocumentNotReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.NotSame(a.FilePath, b.FilePath); public void Dispose() { try { _metadataAsSourceService.CleanupGeneratedFiles(); } finally { Workspace.Dispose(); } } public async Task<ISymbol?> ResolveSymbolAsync(string symbolMetadataName, Compilation? compilation = null) { if (compilation == null) { compilation = await this.DefaultProject.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); } foreach (var reference in compilation.References) { var assemblySymbol = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(reference); Contract.ThrowIfNull(assemblySymbol); var namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(symbolMetadataName); if (namedTypeSymbol != null) { return namedTypeSymbol; } else { // The symbol name could possibly be referring to the member of a named // type. Parse the member symbol name. var lastDotIndex = symbolMetadataName.LastIndexOf('.'); if (lastDotIndex < 0) { // The symbol name is not a member name and the named type was not found // in this assembly continue; } // The member symbol name itself could contain a dot (e.g. '.ctor'), so make // sure we don't cut that off while (lastDotIndex > 0 && symbolMetadataName[lastDotIndex - 1] == '.') { --lastDotIndex; } var memberSymbolName = symbolMetadataName.Substring(lastDotIndex + 1); var namedTypeName = symbolMetadataName.Substring(0, lastDotIndex); namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(namedTypeName); if (namedTypeSymbol != null) { var memberSymbol = namedTypeSymbol.GetMembers() .Where(member => member.MetadataName == memberSymbolName) .FirstOrDefault(); if (memberSymbol != null) { return memberSymbol; } } } } return null; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim"); } private static string DeduceLanguageString(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static TestWorkspace CreateWorkspace( string projectLanguage, IEnumerable<string>? metadataSources, bool includeXmlDocComments, string? sourceWithSymbolReference, string? languageVersion, string? metadataLanguageVersion) { var languageVersionAttribute = languageVersion is null ? "" : $@" LanguageVersion=""{languageVersion}"""; var xmlString = string.Concat(@" <Workspace> <Project Language=""", projectLanguage, @""" CommonReferences=""true"" ReferencesOnDisk=""true""", languageVersionAttribute); xmlString += ">"; metadataSources ??= new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }; foreach (var source in metadataSources) { var metadataLanguage = DeduceLanguageString(source); var metadataLanguageVersionAttribute = metadataLanguageVersion is null ? "" : $@" LanguageVersion=""{metadataLanguageVersion}"""; xmlString = string.Concat(xmlString, $@" <MetadataReferenceFromSource Language=""{metadataLanguage}"" CommonReferences=""true"" {metadataLanguageVersionAttribute} IncludeXmlDocComments=""{includeXmlDocComments}""> <Document FilePath=""MetadataDocument""> {SecurityElement.Escape(source)} </Document> </MetadataReferenceFromSource>"); } if (sourceWithSymbolReference != null) { xmlString = string.Concat(xmlString, string.Format(@" <Document FilePath=""SourceDocument""> {0} </Document>", sourceWithSymbolReference)); } xmlString = string.Concat(xmlString, @" </Project> </Workspace>"); return TestWorkspace.Create(xmlString); } internal Document GetDocument(MetadataAsSourceFile file) { using var reader = File.OpenRead(file.FilePath); var stringText = EncodedStringText.Create(reader); Assert.True(_metadataAsSourceService.TryAddDocumentToWorkspace(file.FilePath, stringText.Container)); return stringText.Container.GetRelatedDocuments().Single(); } internal async Task<ISymbol> GetNavigationSymbolAsync() { var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None); var symbol = semanticModel.GetSymbolInfo(syntaxRoot.FindNode(testDocument.SelectedSpans.Single())).Symbol; Contract.ThrowIfNull(symbol); return symbol; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.CSharp.DecompiledSource; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.MetadataAsSource; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.UnitTests.MetadataAsSource { public abstract partial class AbstractMetadataAsSourceTests { public const string DefaultMetadataSource = "public class C {}"; public const string DefaultSymbolMetadataName = "C"; internal class TestContext : IDisposable { public readonly TestWorkspace Workspace; private readonly IMetadataAsSourceFileService _metadataAsSourceService; public static TestContext Create( string? projectLanguage = null, IEnumerable<string>? metadataSources = null, bool includeXmlDocComments = false, string? sourceWithSymbolReference = null, string? languageVersion = null, string? metadataLanguageVersion = null) { projectLanguage ??= LanguageNames.CSharp; metadataSources ??= SpecializedCollections.EmptyEnumerable<string>(); metadataSources = !metadataSources.Any() ? new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource } : metadataSources; var workspace = CreateWorkspace( projectLanguage, metadataSources, includeXmlDocComments, sourceWithSymbolReference, languageVersion, metadataLanguageVersion); return new TestContext(workspace); } public TestContext(TestWorkspace workspace) { Workspace = workspace; _metadataAsSourceService = Workspace.GetService<IMetadataAsSourceFileService>(); } public Solution CurrentSolution { get { return Workspace.CurrentSolution; } } public Project DefaultProject { get { return this.CurrentSolution.Projects.First(); } } public Task<MetadataAsSourceFile> GenerateSourceAsync(ISymbol symbol, Project? project = null, bool allowDecompilation = false) { project ??= this.DefaultProject; Contract.ThrowIfNull(symbol); // Generate and hold onto the result so it can be disposed of with this context return _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); } public async Task<MetadataAsSourceFile> GenerateSourceAsync(string? symbolMetadataName = null, Project? project = null, bool allowDecompilation = false) { symbolMetadataName ??= AbstractMetadataAsSourceTests.DefaultSymbolMetadataName; project ??= this.DefaultProject; // Get an ISymbol corresponding to the metadata name var compilation = await project.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); var symbol = await ResolveSymbolAsync(symbolMetadataName, compilation); Contract.ThrowIfNull(symbol); if (allowDecompilation) { foreach (var reference in compilation.References) { if (AssemblyResolver.TestAccessor.ContainsInMemoryImage(reference)) { continue; } if (reference is PortableExecutableReference portableExecutable) { Assert.True(File.Exists(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' does not exist for reference '{portableExecutable.Display}'"); Assert.True(Path.IsPathRooted(portableExecutable.FilePath), $"'{portableExecutable.FilePath}' is not a fully-qualified file name"); } else { Assert.True(File.Exists(reference.Display), $"'{reference.Display}' does not exist"); Assert.True(Path.IsPathRooted(reference.Display), $"'{reference.Display}' is not a fully-qualified file name"); } } } // Generate and hold onto the result so it can be disposed of with this context var result = await _metadataAsSourceService.GetGeneratedFileAsync(project, symbol, allowDecompilation); return result; } public static void VerifyResult(MetadataAsSourceFile file, string expected) { var actual = File.ReadAllText(file.FilePath).Trim(); var actualSpan = file.IdentifierLocation.SourceSpan; // Compare exact texts and verify that the location returned is exactly that // indicated by expected MarkupTestFile.GetSpan(expected, out expected, out var expectedSpan); AssertEx.EqualOrDiff(expected, actual); Assert.Equal(expectedSpan.Start, actualSpan.Start); Assert.Equal(expectedSpan.End, actualSpan.End); } public async Task GenerateAndVerifySourceAsync(string symbolMetadataName, string expected, Project? project = null, bool allowDecompilation = false) { var result = await GenerateSourceAsync(symbolMetadataName, project, allowDecompilation); VerifyResult(result, expected); } public static void VerifyDocumentReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.Same(a.FilePath, b.FilePath); public static void VerifyDocumentNotReused(MetadataAsSourceFile a, MetadataAsSourceFile b) => Assert.NotSame(a.FilePath, b.FilePath); public void Dispose() { try { _metadataAsSourceService.CleanupGeneratedFiles(); } finally { Workspace.Dispose(); } } public async Task<ISymbol?> ResolveSymbolAsync(string symbolMetadataName, Compilation? compilation = null) { if (compilation == null) { compilation = await this.DefaultProject.GetRequiredCompilationAsync(CancellationToken.None); var diagnostics = compilation.GetDiagnostics().ToArray(); Assert.Equal(0, diagnostics.Length); } foreach (var reference in compilation.References) { var assemblySymbol = (IAssemblySymbol?)compilation.GetAssemblyOrModuleSymbol(reference); Contract.ThrowIfNull(assemblySymbol); var namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(symbolMetadataName); if (namedTypeSymbol != null) { return namedTypeSymbol; } else { // The symbol name could possibly be referring to the member of a named // type. Parse the member symbol name. var lastDotIndex = symbolMetadataName.LastIndexOf('.'); if (lastDotIndex < 0) { // The symbol name is not a member name and the named type was not found // in this assembly continue; } // The member symbol name itself could contain a dot (e.g. '.ctor'), so make // sure we don't cut that off while (lastDotIndex > 0 && symbolMetadataName[lastDotIndex - 1] == '.') { --lastDotIndex; } var memberSymbolName = symbolMetadataName.Substring(lastDotIndex + 1); var namedTypeName = symbolMetadataName.Substring(0, lastDotIndex); namedTypeSymbol = assemblySymbol.GetTypeByMetadataName(namedTypeName); if (namedTypeSymbol != null) { var memberSymbol = namedTypeSymbol.GetMembers() .Where(member => member.MetadataName == memberSymbolName) .FirstOrDefault(); if (memberSymbol != null) { return memberSymbol; } } } } return null; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim"); } private static string DeduceLanguageString(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static TestWorkspace CreateWorkspace( string projectLanguage, IEnumerable<string>? metadataSources, bool includeXmlDocComments, string? sourceWithSymbolReference, string? languageVersion, string? metadataLanguageVersion) { var languageVersionAttribute = languageVersion is null ? "" : $@" LanguageVersion=""{languageVersion}"""; var xmlString = string.Concat(@" <Workspace> <Project Language=""", projectLanguage, @""" CommonReferences=""true"" ReferencesOnDisk=""true""", languageVersionAttribute); xmlString += ">"; metadataSources ??= new[] { AbstractMetadataAsSourceTests.DefaultMetadataSource }; foreach (var source in metadataSources) { var metadataLanguage = DeduceLanguageString(source); var metadataLanguageVersionAttribute = metadataLanguageVersion is null ? "" : $@" LanguageVersion=""{metadataLanguageVersion}"""; xmlString = string.Concat(xmlString, $@" <MetadataReferenceFromSource Language=""{metadataLanguage}"" CommonReferences=""true"" {metadataLanguageVersionAttribute} IncludeXmlDocComments=""{includeXmlDocComments}""> <Document FilePath=""MetadataDocument""> {SecurityElement.Escape(source)} </Document> </MetadataReferenceFromSource>"); } if (sourceWithSymbolReference != null) { xmlString = string.Concat(xmlString, string.Format(@" <Document FilePath=""SourceDocument""> {0} </Document>", sourceWithSymbolReference)); } xmlString = string.Concat(xmlString, @" </Project> </Workspace>"); return TestWorkspace.Create(xmlString); } internal Document GetDocument(MetadataAsSourceFile file) { using var reader = File.OpenRead(file.FilePath); var stringText = EncodedStringText.Create(reader); Assert.True(_metadataAsSourceService.TryAddDocumentToWorkspace(file.FilePath, stringText.Container)); return stringText.Container.GetRelatedDocuments().Single(); } internal async Task<ISymbol> GetNavigationSymbolAsync() { var testDocument = Workspace.Documents.Single(d => d.FilePath == "SourceDocument"); var document = Workspace.CurrentSolution.GetRequiredDocument(testDocument.Id); var syntaxRoot = await document.GetRequiredSyntaxRootAsync(CancellationToken.None); var semanticModel = await document.GetRequiredSemanticModelAsync(CancellationToken.None); var symbol = semanticModel.GetSymbolInfo(syntaxRoot.FindNode(testDocument.SelectedSpans.Single())).Symbol; Contract.ThrowIfNull(symbol); return symbol; } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Core/Def/Implementation/TableDataSource/MiscTodoListTableControlEventProcessorProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(ITableControlEventProcessorProvider))] [DataSourceType(StandardTableDataSources.CommentTableDataSource)] [DataSource(MiscellaneousTodoListTableWorkspaceEventListener.IdentifierString)] [Name(Name)] [Order(Before = "default")] internal sealed class MiscTodoListTableControlEventProcessorProvider : AbstractTableControlEventProcessorProvider<TodoTableItem> { internal const string Name = "Misc C#/VB Todo List Table Event Processor"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MiscTodoListTableControlEventProcessorProvider() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.VisualStudio.Shell.TableControl; using Microsoft.VisualStudio.Shell.TableManager; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource { [Export(typeof(ITableControlEventProcessorProvider))] [DataSourceType(StandardTableDataSources.CommentTableDataSource)] [DataSource(MiscellaneousTodoListTableWorkspaceEventListener.IdentifierString)] [Name(Name)] [Order(Before = "default")] internal sealed class MiscTodoListTableControlEventProcessorProvider : AbstractTableControlEventProcessorProvider<TodoTableItem> { internal const string Name = "Misc C#/VB Todo List Table Event Processor"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public MiscTodoListTableControlEventProcessorProvider() { } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CompilationUnitSyntaxExtensions.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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class CompilationUnitSyntaxExtensions { public static bool CanAddUsingDirectives(this SyntaxNode contextNode, Document document, CancellationToken cancellationToken) => CanAddUsingDirectives(contextNode, document.CanAddImportsInHiddenRegions(), cancellationToken); public static bool CanAddUsingDirectives(this SyntaxNode contextNode, bool allowInHiddenRegions, CancellationToken cancellationToken) { var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>(); if (usingDirectiveAncestor?.Parent is CompilationUnitSyntax) { // We are inside a top level using directive (i.e. one that's directly in the compilation unit). return false; } if (!allowInHiddenRegions && contextNode.SyntaxTree.HasHiddenRegions()) { var namespaceDeclaration = contextNode.GetInnermostNamespaceDeclarationWithUsings(); var root = (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken); var span = GetUsingsSpan(root, namespaceDeclaration); if (contextNode.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken)) { return false; } } if (cancellationToken.IsCancellationRequested) { return false; } return true; } private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax? namespaceDeclaration) { if (namespaceDeclaration != null) { var usings = namespaceDeclaration.Usings; var start = usings.First().SpanStart; var end = usings.Last().Span.End; return TextSpan.FromBounds(start, end); } else { var rootUsings = root.Usings; if (rootUsings.Any()) { var start = rootUsings.First().SpanStart; var end = rootUsings.Last().Span.End; return TextSpan.FromBounds(start, end); } else { var start = 0; var end = root.Members.Any() ? root.Members.First().GetFirstToken().Span.End : root.Span.End; return TextSpan.FromBounds(start, end); } } } public static CompilationUnitSyntax AddUsingDirective( this CompilationUnitSyntax root, UsingDirectiveSyntax usingDirective, SyntaxNode contextNode, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { return root.AddUsingDirectives(new[] { usingDirective }, contextNode, placeSystemNamespaceFirst, annotations); } public static CompilationUnitSyntax AddUsingDirectives( this CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives, SyntaxNode contextNode, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { if (!usingDirectives.Any()) { return root; } var firstOuterNamespaceWithUsings = contextNode.GetInnermostNamespaceDeclarationWithUsings(); if (firstOuterNamespaceWithUsings == null) { return root.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations); } else { var newNamespace = firstOuterNamespaceWithUsings.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations); return root.ReplaceNode(firstOuterNamespaceWithUsings, newNamespace); } } public static CompilationUnitSyntax AddUsingDirectives( this CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { if (usingDirectives.Count == 0) { return root; } var usings = AddUsingDirectives(root, usingDirectives); // Keep usings sorted if they were originally sorted. usings.SortUsingDirectives(root.Usings, placeSystemNamespaceFirst); if (root.Externs.Count == 0) { root = AddImportHelpers.MoveTrivia( CSharpSyntaxFacts.Instance, root, root.Usings, usings); } return root.WithUsings( usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToSyntaxList()); } private static List<UsingDirectiveSyntax> AddUsingDirectives( CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives) { // We need to try and not place the using inside of a directive if possible. var usings = new List<UsingDirectiveSyntax>(); var endOfList = root.Usings.Count - 1; var startOfLastDirective = -1; var endOfLastDirective = -1; for (var i = 0; i < root.Usings.Count; i++) { if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.IfDirectiveTrivia))) { startOfLastDirective = i; } if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia))) { endOfLastDirective = i; } } // if the entire using is in a directive or there is a using list at the end outside of the directive add the using at the end, // else place it before the last directive. usings.AddRange(root.Usings); if ((startOfLastDirective == 0 && (endOfLastDirective == endOfList || endOfLastDirective == -1)) || (startOfLastDirective == -1 && endOfLastDirective == -1) || (endOfLastDirective != endOfList && endOfLastDirective != -1)) { usings.AddRange(usingDirectives); } else { usings.InsertRange(startOfLastDirective, usingDirectives); } return usings; } } }
// Licensed to the .NET Foundation under one or more 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.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.AddImports; using Microsoft.CodeAnalysis.CSharp.LanguageServices; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal static class CompilationUnitSyntaxExtensions { public static bool CanAddUsingDirectives(this SyntaxNode contextNode, Document document, CancellationToken cancellationToken) => CanAddUsingDirectives(contextNode, document.CanAddImportsInHiddenRegions(), cancellationToken); public static bool CanAddUsingDirectives(this SyntaxNode contextNode, bool allowInHiddenRegions, CancellationToken cancellationToken) { var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>(); if (usingDirectiveAncestor?.Parent is CompilationUnitSyntax) { // We are inside a top level using directive (i.e. one that's directly in the compilation unit). return false; } if (!allowInHiddenRegions && contextNode.SyntaxTree.HasHiddenRegions()) { var namespaceDeclaration = contextNode.GetInnermostNamespaceDeclarationWithUsings(); var root = (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken); var span = GetUsingsSpan(root, namespaceDeclaration); if (contextNode.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken)) { return false; } } if (cancellationToken.IsCancellationRequested) { return false; } return true; } private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax? namespaceDeclaration) { if (namespaceDeclaration != null) { var usings = namespaceDeclaration.Usings; var start = usings.First().SpanStart; var end = usings.Last().Span.End; return TextSpan.FromBounds(start, end); } else { var rootUsings = root.Usings; if (rootUsings.Any()) { var start = rootUsings.First().SpanStart; var end = rootUsings.Last().Span.End; return TextSpan.FromBounds(start, end); } else { var start = 0; var end = root.Members.Any() ? root.Members.First().GetFirstToken().Span.End : root.Span.End; return TextSpan.FromBounds(start, end); } } } public static CompilationUnitSyntax AddUsingDirective( this CompilationUnitSyntax root, UsingDirectiveSyntax usingDirective, SyntaxNode contextNode, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { return root.AddUsingDirectives(new[] { usingDirective }, contextNode, placeSystemNamespaceFirst, annotations); } public static CompilationUnitSyntax AddUsingDirectives( this CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives, SyntaxNode contextNode, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { if (!usingDirectives.Any()) { return root; } var firstOuterNamespaceWithUsings = contextNode.GetInnermostNamespaceDeclarationWithUsings(); if (firstOuterNamespaceWithUsings == null) { return root.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations); } else { var newNamespace = firstOuterNamespaceWithUsings.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations); return root.ReplaceNode(firstOuterNamespaceWithUsings, newNamespace); } } public static CompilationUnitSyntax AddUsingDirectives( this CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives, bool placeSystemNamespaceFirst, params SyntaxAnnotation[] annotations) { if (usingDirectives.Count == 0) { return root; } var usings = AddUsingDirectives(root, usingDirectives); // Keep usings sorted if they were originally sorted. usings.SortUsingDirectives(root.Usings, placeSystemNamespaceFirst); if (root.Externs.Count == 0) { root = AddImportHelpers.MoveTrivia( CSharpSyntaxFacts.Instance, root, root.Usings, usings); } return root.WithUsings( usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToSyntaxList()); } private static List<UsingDirectiveSyntax> AddUsingDirectives( CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives) { // We need to try and not place the using inside of a directive if possible. var usings = new List<UsingDirectiveSyntax>(); var endOfList = root.Usings.Count - 1; var startOfLastDirective = -1; var endOfLastDirective = -1; for (var i = 0; i < root.Usings.Count; i++) { if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.IfDirectiveTrivia))) { startOfLastDirective = i; } if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia))) { endOfLastDirective = i; } } // if the entire using is in a directive or there is a using list at the end outside of the directive add the using at the end, // else place it before the last directive. usings.AddRange(root.Usings); if ((startOfLastDirective == 0 && (endOfLastDirective == endOfList || endOfLastDirective == -1)) || (startOfLastDirective == -1 && endOfLastDirective == -1) || (endOfLastDirective != endOfList && endOfLastDirective != -1)) { usings.AddRange(usingDirectives); } else { usings.InsertRange(startOfLastDirective, usingDirectives); } return usings; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/Core/Portable/Syntax/InternalSyntax/SyntaxDiagnosticInfoList.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { // Avoid implementing IEnumerable so we do not get any unintentional boxing. internal struct SyntaxDiagnosticInfoList { private readonly GreenNode _node; internal SyntaxDiagnosticInfoList(GreenNode node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } internal bool Any(Func<DiagnosticInfo, bool> predicate) { var enumerator = GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) return true; } return false; } public struct Enumerator { private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private NodeIteration[]? _stack; private int _count; public DiagnosticInfo Current { get; private set; } internal Enumerator(GreenNode node) { Current = null!; _stack = null; _count = 0; if (node != null && node.ContainsDiagnostics) { _stack = new NodeIteration[8]; this.PushNodeOrToken(node); } } public bool MoveNext() { while (_count > 0) { var diagIndex = _stack![_count - 1].DiagnosticIndex; var node = _stack[_count - 1].Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; Current = diags[diagIndex]; _stack[_count - 1].DiagnosticIndex = diagIndex; return true; } var slotIndex = _stack[_count - 1].SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null || !child.ContainsDiagnostics) { goto tryAgain; } _stack[_count - 1].SlotIndex = slotIndex; this.PushNodeOrToken(child); } else { this.Pop(); } } return false; } private void PushNodeOrToken(GreenNode node) { if (node.IsToken) { this.PushToken(node); } else { this.Push(node); } } private void PushToken(GreenNode token) { var trailing = token.GetTrailingTriviaCore(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTriviaCore(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { RoslynDebug.Assert(_stack is object); if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } private void Pop() { _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. using System; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Syntax.InternalSyntax { // Avoid implementing IEnumerable so we do not get any unintentional boxing. internal struct SyntaxDiagnosticInfoList { private readonly GreenNode _node; internal SyntaxDiagnosticInfoList(GreenNode node) { _node = node; } public Enumerator GetEnumerator() { return new Enumerator(_node); } internal bool Any(Func<DiagnosticInfo, bool> predicate) { var enumerator = GetEnumerator(); while (enumerator.MoveNext()) { if (predicate(enumerator.Current)) return true; } return false; } public struct Enumerator { private struct NodeIteration { internal readonly GreenNode Node; internal int DiagnosticIndex; internal int SlotIndex; internal NodeIteration(GreenNode node) { this.Node = node; this.SlotIndex = -1; this.DiagnosticIndex = -1; } } private NodeIteration[]? _stack; private int _count; public DiagnosticInfo Current { get; private set; } internal Enumerator(GreenNode node) { Current = null!; _stack = null; _count = 0; if (node != null && node.ContainsDiagnostics) { _stack = new NodeIteration[8]; this.PushNodeOrToken(node); } } public bool MoveNext() { while (_count > 0) { var diagIndex = _stack![_count - 1].DiagnosticIndex; var node = _stack[_count - 1].Node; var diags = node.GetDiagnostics(); if (diagIndex < diags.Length - 1) { diagIndex++; Current = diags[diagIndex]; _stack[_count - 1].DiagnosticIndex = diagIndex; return true; } var slotIndex = _stack[_count - 1].SlotIndex; tryAgain: if (slotIndex < node.SlotCount - 1) { slotIndex++; var child = node.GetSlot(slotIndex); if (child == null || !child.ContainsDiagnostics) { goto tryAgain; } _stack[_count - 1].SlotIndex = slotIndex; this.PushNodeOrToken(child); } else { this.Pop(); } } return false; } private void PushNodeOrToken(GreenNode node) { if (node.IsToken) { this.PushToken(node); } else { this.Push(node); } } private void PushToken(GreenNode token) { var trailing = token.GetTrailingTriviaCore(); if (trailing != null) { this.Push(trailing); } this.Push(token); var leading = token.GetLeadingTriviaCore(); if (leading != null) { this.Push(leading); } } private void Push(GreenNode node) { RoslynDebug.Assert(_stack is object); if (_count >= _stack.Length) { var tmp = new NodeIteration[_stack.Length * 2]; Array.Copy(_stack, tmp, _stack.Length); _stack = tmp; } _stack[_count] = new NodeIteration(node); _count++; } private void Pop() { _count--; } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Portable/Syntax/QualifiedNameSyntax.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class QualifiedNameSyntax : NameSyntax { // This override is only intended to support cases where a caller has a value statically typed as NameSyntax in hand // and neither knows nor cares to determine whether that name is qualified or not. // If a value is statically typed as a QualifiedNameSyntax calling Right directly is preferred. internal override SimpleNameSyntax GetUnqualifiedName() { return Right; } internal override string ErrorDisplayName() { return Left.ErrorDisplayName() + "." + Right.ErrorDisplayName(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Syntax { public sealed partial class QualifiedNameSyntax : NameSyntax { // This override is only intended to support cases where a caller has a value statically typed as NameSyntax in hand // and neither knows nor cares to determine whether that name is qualified or not. // If a value is statically typed as a QualifiedNameSyntax calling Right directly is preferred. internal override SimpleNameSyntax GetUnqualifiedName() { return Right; } internal override string ErrorDisplayName() { return Left.ErrorDisplayName() + "." + Right.ErrorDisplayName(); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/VisualBasicTest/Extensions/StatementSyntaxExtensionTests.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.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports System.Threading Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Extensions Public Class StatementSyntaxExtensionTests Private Shared Sub TestStatementDeclarationWithPublicModifier(Of T As StatementSyntax)(node As T) Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Dim newNode = DirectCast(node.WithModifiers(modifierList), T) Dim actual = newNode.GetModifiers().First().ToString() Assert.Equal("Public", actual) End Sub Private Shared Sub VerifyTokenName(Of T As DeclarationStatementSyntax)(code As String, expectedName As String) Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of T).First() Dim actualNameToken = node.GetNameToken() Assert.Equal(expectedName, actualNameToken.ToString()) End Sub <Fact> Public Sub MethodReturnType() Dim methodDeclaration = SyntaxFactory.FunctionStatement(attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.Identifier("F1"), typeParameterList:=Nothing, parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword))), handlesClause:=Nothing, implementsClause:=Nothing) Assert.True(methodDeclaration.HasReturnType()) Dim result = methodDeclaration.GetReturnType() Dim returnTypeName = result.ToString() Assert.Equal("Integer", returnTypeName) End Sub <Fact> Public Sub PropertyReturnType() Dim propertyDeclaration = SyntaxFactory.PropertyStatement(attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.Identifier("P1"), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword))), initializer:=Nothing, implementsClause:=Nothing) Assert.True(propertyDeclaration.HasReturnType()) Dim result = propertyDeclaration.GetReturnType() Dim returnTypeName = result.ToString() Assert.Equal("Byte", returnTypeName) End Sub Private Shared Sub TestTypeBlockWithPublicModifier(Of T As TypeBlockSyntax)(code As String) Dim node = SyntaxFactory.ParseCompilationUnit(code).Members.First() Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Dim newNode = DirectCast(node.WithModifiers(modifierList), T) Dim actual = newNode.GetModifiers().First().ToString() Assert.Equal("Public", actual) End Sub <Fact> Public Sub GetClassStatementModifiers() Dim code = <String>Public Class C</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of ClassStatementSyntax).First() Dim actualModifierName = node.Modifiers().First().ToString() Assert.Equal("Public", actualModifierName) End Sub <Fact> Public Sub GetEnumStatementModifiers() Dim code = <String>Public Enum E</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EnumStatementSyntax).First() Dim actualModifierName = node.Modifiers().First().ToString() Assert.Equal("Public", actualModifierName) End Sub <Fact> Public Sub InterfaceBlockWithPublicModifier() Dim code = <String>Interface I End Interface</String>.Value TestTypeBlockWithPublicModifier(Of InterfaceBlockSyntax)(code) End Sub <Fact> Public Sub ModuleBlockWithPublicModifier() Dim code = <String>Module M End Module</String>.Value TestTypeBlockWithPublicModifier(Of ModuleBlockSyntax)(code) End Sub <Fact> Public Sub StructureBlockWithPublicModifier() Dim code = <string>Structure S End Structure</string>.Value TestTypeBlockWithPublicModifier(Of StructureBlockSyntax)(code) End Sub <Fact> Public Sub EnumBlockWithPublicModifier() Dim code = <String>Enum E End Enum</String>.Value Dim node = DirectCast(SyntaxFactory.ParseCompilationUnit(code).Members.First(), EnumBlockSyntax) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub ClassStatementWithPublicModifier() Dim node = SyntaxFactory.ClassStatement(SyntaxFactory.Identifier("C")) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub EnumStatementWithPublicModifier() Dim node = SyntaxFactory.EnumStatement(SyntaxFactory.Identifier("E")) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub FieldDeclarationWithPublicModifier() Dim code = <String>Class C dim _field as Integer = 1 End Class</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of FieldDeclarationSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub EventBlockWithPublicModifier() Dim code = <String>Custom Event E As EventHandler End Event</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EventBlockSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub EventStatementWithPublicModifier() Dim node = SyntaxFactory.EventStatement(SyntaxFactory.Identifier("E")) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub PropertyBlockWithPublicModifier() Dim code = <String>Property P as Integer End Property</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of PropertyBlockSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub SubBlockWithPublicModifier() Dim code = <String>Sub Goo End Sub</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of MethodBlockSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub VerifyClassNameToken() Dim code = <String>Class C End Class</String>.Value VerifyTokenName(Of ClassBlockSyntax)(code, "C") End Sub <Fact> Public Sub VerifyInterfaceNameToken() Dim code = <String>Interface I End Interface</String>.Value VerifyTokenName(Of InterfaceBlockSyntax)(code, "I") End Sub <Fact> Public Sub VerifyStructureNameToken() Dim code = <String>Structure S End Structure</String>.Value VerifyTokenName(Of StructureBlockSyntax)(code, "S") End Sub <Fact> Public Sub VerifyModuleNameToken() Dim code = <String>Module M End Module</String>.Value VerifyTokenName(Of ModuleBlockSyntax)(code, "M") End Sub <Fact> Public Sub VerifyStructureStatementNameToken() Dim code = <String>Structure SS </String>.Value VerifyTokenName(Of StructureStatementSyntax)(code, "SS") End Sub <Fact> Public Sub VerifyConstructorNameTokenIsNothing() Dim code = <String>Class C Sub New() End Class</String>.Value VerifyTokenName(Of SubNewStatementSyntax)(code, "") End Sub <Fact, WorkItem(552823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552823")> Public Sub TestIsInStatementBlockOfKindForBrokenCode() Dim code = <String>End Sub End Module End Namespace d</String>.Value Dim tree = SyntaxFactory.ParseSyntaxTree(code) Dim token = tree.GetRoot() _ .DescendantTokens() _ .Where(Function(t) t.Kind = SyntaxKind.NamespaceKeyword) _ .First() For position = token.SpanStart To token.Span.End Dim targetToken = tree.GetTargetToken(position, CancellationToken.None) tree.IsInStatementBlockOfKind(position, targetToken, CancellationToken.None) Next 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.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery Imports System.Threading Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Extensions Public Class StatementSyntaxExtensionTests Private Shared Sub TestStatementDeclarationWithPublicModifier(Of T As StatementSyntax)(node As T) Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Dim newNode = DirectCast(node.WithModifiers(modifierList), T) Dim actual = newNode.GetModifiers().First().ToString() Assert.Equal("Public", actual) End Sub Private Shared Sub VerifyTokenName(Of T As DeclarationStatementSyntax)(code As String, expectedName As String) Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of T).First() Dim actualNameToken = node.GetNameToken() Assert.Equal(expectedName, actualNameToken.ToString()) End Sub <Fact> Public Sub MethodReturnType() Dim methodDeclaration = SyntaxFactory.FunctionStatement(attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.Identifier("F1"), typeParameterList:=Nothing, parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.IntegerKeyword))), handlesClause:=Nothing, implementsClause:=Nothing) Assert.True(methodDeclaration.HasReturnType()) Dim result = methodDeclaration.GetReturnType() Dim returnTypeName = result.ToString() Assert.Equal("Integer", returnTypeName) End Sub <Fact> Public Sub PropertyReturnType() Dim propertyDeclaration = SyntaxFactory.PropertyStatement(attributeLists:=Nothing, modifiers:=Nothing, identifier:=SyntaxFactory.Identifier("P1"), parameterList:=Nothing, asClause:=SyntaxFactory.SimpleAsClause(SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ByteKeyword))), initializer:=Nothing, implementsClause:=Nothing) Assert.True(propertyDeclaration.HasReturnType()) Dim result = propertyDeclaration.GetReturnType() Dim returnTypeName = result.ToString() Assert.Equal("Byte", returnTypeName) End Sub Private Shared Sub TestTypeBlockWithPublicModifier(Of T As TypeBlockSyntax)(code As String) Dim node = SyntaxFactory.ParseCompilationUnit(code).Members.First() Dim modifierList = SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Dim newNode = DirectCast(node.WithModifiers(modifierList), T) Dim actual = newNode.GetModifiers().First().ToString() Assert.Equal("Public", actual) End Sub <Fact> Public Sub GetClassStatementModifiers() Dim code = <String>Public Class C</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of ClassStatementSyntax).First() Dim actualModifierName = node.Modifiers().First().ToString() Assert.Equal("Public", actualModifierName) End Sub <Fact> Public Sub GetEnumStatementModifiers() Dim code = <String>Public Enum E</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EnumStatementSyntax).First() Dim actualModifierName = node.Modifiers().First().ToString() Assert.Equal("Public", actualModifierName) End Sub <Fact> Public Sub InterfaceBlockWithPublicModifier() Dim code = <String>Interface I End Interface</String>.Value TestTypeBlockWithPublicModifier(Of InterfaceBlockSyntax)(code) End Sub <Fact> Public Sub ModuleBlockWithPublicModifier() Dim code = <String>Module M End Module</String>.Value TestTypeBlockWithPublicModifier(Of ModuleBlockSyntax)(code) End Sub <Fact> Public Sub StructureBlockWithPublicModifier() Dim code = <string>Structure S End Structure</string>.Value TestTypeBlockWithPublicModifier(Of StructureBlockSyntax)(code) End Sub <Fact> Public Sub EnumBlockWithPublicModifier() Dim code = <String>Enum E End Enum</String>.Value Dim node = DirectCast(SyntaxFactory.ParseCompilationUnit(code).Members.First(), EnumBlockSyntax) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub ClassStatementWithPublicModifier() Dim node = SyntaxFactory.ClassStatement(SyntaxFactory.Identifier("C")) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub EnumStatementWithPublicModifier() Dim node = SyntaxFactory.EnumStatement(SyntaxFactory.Identifier("E")) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub FieldDeclarationWithPublicModifier() Dim code = <String>Class C dim _field as Integer = 1 End Class</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of FieldDeclarationSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub EventBlockWithPublicModifier() Dim code = <String>Custom Event E As EventHandler End Event</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of EventBlockSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub EventStatementWithPublicModifier() Dim node = SyntaxFactory.EventStatement(SyntaxFactory.Identifier("E")) TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub PropertyBlockWithPublicModifier() Dim code = <String>Property P as Integer End Property</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of PropertyBlockSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub SubBlockWithPublicModifier() Dim code = <String>Sub Goo End Sub</String>.Value Dim node = SyntaxFactory.ParseCompilationUnit(code).DescendantNodes.OfType(Of MethodBlockSyntax).First() TestStatementDeclarationWithPublicModifier(node) End Sub <Fact> Public Sub VerifyClassNameToken() Dim code = <String>Class C End Class</String>.Value VerifyTokenName(Of ClassBlockSyntax)(code, "C") End Sub <Fact> Public Sub VerifyInterfaceNameToken() Dim code = <String>Interface I End Interface</String>.Value VerifyTokenName(Of InterfaceBlockSyntax)(code, "I") End Sub <Fact> Public Sub VerifyStructureNameToken() Dim code = <String>Structure S End Structure</String>.Value VerifyTokenName(Of StructureBlockSyntax)(code, "S") End Sub <Fact> Public Sub VerifyModuleNameToken() Dim code = <String>Module M End Module</String>.Value VerifyTokenName(Of ModuleBlockSyntax)(code, "M") End Sub <Fact> Public Sub VerifyStructureStatementNameToken() Dim code = <String>Structure SS </String>.Value VerifyTokenName(Of StructureStatementSyntax)(code, "SS") End Sub <Fact> Public Sub VerifyConstructorNameTokenIsNothing() Dim code = <String>Class C Sub New() End Class</String>.Value VerifyTokenName(Of SubNewStatementSyntax)(code, "") End Sub <Fact, WorkItem(552823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552823")> Public Sub TestIsInStatementBlockOfKindForBrokenCode() Dim code = <String>End Sub End Module End Namespace d</String>.Value Dim tree = SyntaxFactory.ParseSyntaxTree(code) Dim token = tree.GetRoot() _ .DescendantTokens() _ .Where(Function(t) t.Kind = SyntaxKind.NamespaceKeyword) _ .First() For position = token.SpanStart To token.Span.End Dim targetToken = tree.GetTargetToken(position, CancellationToken.None) tree.IsInStatementBlockOfKind(position, targetToken, CancellationToken.None) Next End Sub End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/VisualBasic/LineCommit/CommitViewManager.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit ''' <summary> ''' This class watches for view-based events in relation to a specific subject buffer and passes along commit operations. ''' </summary> Friend Class CommitViewManager Private ReadOnly _view As ITextView Private ReadOnly _commitBufferManagerFactory As CommitBufferManagerFactory Private ReadOnly _textBufferAssociatedViewService As ITextBufferAssociatedViewService Private ReadOnly _textUndoHistoryRegistry As ITextUndoHistoryRegistry Private ReadOnly _uiThreadOperationExecutor As IUIThreadOperationExecutor Public Sub New(view As ITextView, commitBufferManagerFactory As CommitBufferManagerFactory, textBufferAssociatedViewService As ITextBufferAssociatedViewService, textUndoHistoryRegistry As ITextUndoHistoryRegistry, uiThreadOperationExecutor As IUIThreadOperationExecutor) _view = view _commitBufferManagerFactory = commitBufferManagerFactory _textBufferAssociatedViewService = textBufferAssociatedViewService _textUndoHistoryRegistry = textUndoHistoryRegistry _uiThreadOperationExecutor = uiThreadOperationExecutor AddHandler _view.Caret.PositionChanged, AddressOf OnCaretPositionChanged AddHandler _view.LostAggregateFocus, AddressOf OnLostAggregateFocus AddHandler _view.Closed, AddressOf OnViewClosed End Sub Public Sub Disconnect() RemoveHandler _view.Caret.PositionChanged, AddressOf OnCaretPositionChanged RemoveHandler _view.LostAggregateFocus, AddressOf OnLostAggregateFocus RemoveHandler _view.Closed, AddressOf OnViewClosed End Sub Private Sub OnCaretPositionChanged(sender As Object, e As CaretPositionChangedEventArgs) Dim oldSnapshotPoint = MapDownToPoint(e.OldPosition) Dim newSnapshotPoint = MapDownToPoint(e.NewPosition) If Not oldSnapshotPoint.HasValue Then Return End If Dim oldBuffer = oldSnapshotPoint.Value.Snapshot.TextBuffer Dim newBuffer = If(newSnapshotPoint.HasValue, newSnapshotPoint.Value.Snapshot.TextBuffer, Nothing) _uiThreadOperationExecutor.Execute( VBEditorResources.Line_commit, VBEditorResources.Committing_line, allowCancellation:=True, showProgress:=False, action:= Sub(context) ' If our buffers changed, then we commit the old one If oldBuffer IsNot newBuffer Then CommitBufferForCaretMovement(oldBuffer, e, context.UserCancellationToken) Return End If ' We're in the same snapshot. Are we on the same line? Dim commitBufferManager = _commitBufferManagerFactory.CreateForBuffer(newBuffer) If CommitBufferManager.IsMovementBetweenStatements(oldSnapshotPoint.Value, newSnapshotPoint.Value, context.UserCancellationToken) Then CommitBufferForCaretMovement(oldBuffer, e, context.UserCancellationToken) End If End Sub) End Sub Private Sub CommitBufferForCaretMovement(buffer As ITextBuffer, e As CaretPositionChangedEventArgs, cancellationToken As CancellationToken) Dim commitBufferManager = _commitBufferManagerFactory.CreateForBuffer(buffer) If commitBufferManager.HasDirtyRegion Then ' In projection buffer scenarios, the text undo history is associated with the surface buffer, so the ' following line's usage of the surface buffer is correct Using transaction = _textUndoHistoryRegistry.GetHistory(_view.TextBuffer).CreateTransaction(VBEditorResources.Visual_Basic_Pretty_List) Dim beforeUndoPrimitive As New BeforeCommitCaretMoveUndoPrimitive(buffer, _textBufferAssociatedViewService, e.OldPosition) transaction.AddUndo(beforeUndoPrimitive) Dim beforeCommitVersion = buffer.CurrentSnapshot.Version Dim subjectBufferCaretPosition = MapDownToPoint(e.OldPosition) commitBufferManager.CommitDirty(isExplicitFormat:=False, cancellationToken:=cancellationToken) If buffer.CurrentSnapshot.Version Is beforeCommitVersion Then transaction.Cancel() Return End If beforeUndoPrimitive.MarkAsActive() transaction.AddUndo(New AfterCommitCaretMoveUndoPrimitive(buffer, _textBufferAssociatedViewService, _view.Caret.Position)) transaction.Complete() End Using End If End Sub Private Function MapDownToPoint(caretPosition As CaretPosition) As SnapshotPoint? Return _view.BufferGraph.MapDownToFirstMatch(caretPosition.BufferPosition, PointTrackingMode.Positive, Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType), caretPosition.Affinity) End Function Private Sub OnViewClosed(sender As Object, e As EventArgs) Disconnect() End Sub Private Sub OnLostAggregateFocus(sender As Object, e As EventArgs) _uiThreadOperationExecutor.Execute( "Commit", VBEditorResources.Committing_line, allowCancellation:=True, showProgress:=False, action:= Sub(context) For Each buffer In _view.BufferGraph.GetTextBuffers(Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType)) _commitBufferManagerFactory.CreateForBuffer(buffer).CommitDirty(isExplicitFormat:=False, cancellationToken:=context.UserCancellationToken) Next End Sub) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Operations Imports Microsoft.VisualStudio.Utilities Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit ''' <summary> ''' This class watches for view-based events in relation to a specific subject buffer and passes along commit operations. ''' </summary> Friend Class CommitViewManager Private ReadOnly _view As ITextView Private ReadOnly _commitBufferManagerFactory As CommitBufferManagerFactory Private ReadOnly _textBufferAssociatedViewService As ITextBufferAssociatedViewService Private ReadOnly _textUndoHistoryRegistry As ITextUndoHistoryRegistry Private ReadOnly _uiThreadOperationExecutor As IUIThreadOperationExecutor Public Sub New(view As ITextView, commitBufferManagerFactory As CommitBufferManagerFactory, textBufferAssociatedViewService As ITextBufferAssociatedViewService, textUndoHistoryRegistry As ITextUndoHistoryRegistry, uiThreadOperationExecutor As IUIThreadOperationExecutor) _view = view _commitBufferManagerFactory = commitBufferManagerFactory _textBufferAssociatedViewService = textBufferAssociatedViewService _textUndoHistoryRegistry = textUndoHistoryRegistry _uiThreadOperationExecutor = uiThreadOperationExecutor AddHandler _view.Caret.PositionChanged, AddressOf OnCaretPositionChanged AddHandler _view.LostAggregateFocus, AddressOf OnLostAggregateFocus AddHandler _view.Closed, AddressOf OnViewClosed End Sub Public Sub Disconnect() RemoveHandler _view.Caret.PositionChanged, AddressOf OnCaretPositionChanged RemoveHandler _view.LostAggregateFocus, AddressOf OnLostAggregateFocus RemoveHandler _view.Closed, AddressOf OnViewClosed End Sub Private Sub OnCaretPositionChanged(sender As Object, e As CaretPositionChangedEventArgs) Dim oldSnapshotPoint = MapDownToPoint(e.OldPosition) Dim newSnapshotPoint = MapDownToPoint(e.NewPosition) If Not oldSnapshotPoint.HasValue Then Return End If Dim oldBuffer = oldSnapshotPoint.Value.Snapshot.TextBuffer Dim newBuffer = If(newSnapshotPoint.HasValue, newSnapshotPoint.Value.Snapshot.TextBuffer, Nothing) _uiThreadOperationExecutor.Execute( VBEditorResources.Line_commit, VBEditorResources.Committing_line, allowCancellation:=True, showProgress:=False, action:= Sub(context) ' If our buffers changed, then we commit the old one If oldBuffer IsNot newBuffer Then CommitBufferForCaretMovement(oldBuffer, e, context.UserCancellationToken) Return End If ' We're in the same snapshot. Are we on the same line? Dim commitBufferManager = _commitBufferManagerFactory.CreateForBuffer(newBuffer) If CommitBufferManager.IsMovementBetweenStatements(oldSnapshotPoint.Value, newSnapshotPoint.Value, context.UserCancellationToken) Then CommitBufferForCaretMovement(oldBuffer, e, context.UserCancellationToken) End If End Sub) End Sub Private Sub CommitBufferForCaretMovement(buffer As ITextBuffer, e As CaretPositionChangedEventArgs, cancellationToken As CancellationToken) Dim commitBufferManager = _commitBufferManagerFactory.CreateForBuffer(buffer) If commitBufferManager.HasDirtyRegion Then ' In projection buffer scenarios, the text undo history is associated with the surface buffer, so the ' following line's usage of the surface buffer is correct Using transaction = _textUndoHistoryRegistry.GetHistory(_view.TextBuffer).CreateTransaction(VBEditorResources.Visual_Basic_Pretty_List) Dim beforeUndoPrimitive As New BeforeCommitCaretMoveUndoPrimitive(buffer, _textBufferAssociatedViewService, e.OldPosition) transaction.AddUndo(beforeUndoPrimitive) Dim beforeCommitVersion = buffer.CurrentSnapshot.Version Dim subjectBufferCaretPosition = MapDownToPoint(e.OldPosition) commitBufferManager.CommitDirty(isExplicitFormat:=False, cancellationToken:=cancellationToken) If buffer.CurrentSnapshot.Version Is beforeCommitVersion Then transaction.Cancel() Return End If beforeUndoPrimitive.MarkAsActive() transaction.AddUndo(New AfterCommitCaretMoveUndoPrimitive(buffer, _textBufferAssociatedViewService, _view.Caret.Position)) transaction.Complete() End Using End If End Sub Private Function MapDownToPoint(caretPosition As CaretPosition) As SnapshotPoint? Return _view.BufferGraph.MapDownToFirstMatch(caretPosition.BufferPosition, PointTrackingMode.Positive, Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType), caretPosition.Affinity) End Function Private Sub OnViewClosed(sender As Object, e As EventArgs) Disconnect() End Sub Private Sub OnLostAggregateFocus(sender As Object, e As EventArgs) _uiThreadOperationExecutor.Execute( "Commit", VBEditorResources.Committing_line, allowCancellation:=True, showProgress:=False, action:= Sub(context) For Each buffer In _view.BufferGraph.GetTextBuffers(Function(b) b.ContentType.IsOfType(ContentTypeNames.VisualBasicContentType)) _commitBufferManagerFactory.CreateForBuffer(buffer).CommitDirty(isExplicitFormat:=False, cancellationToken:=context.UserCancellationToken) Next End Sub) End Sub End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Test2/Rename/CSharp/ImplicitReferenceConflictTests.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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class ImplicitReferenceConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextCausesConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class B { public int Current { get; set; } public bool [|$$MoveNext|]() { return false; } } class C { static void Main() { foreach (var x in {|foreachconflict:new C()|}) { } } public B GetEnumerator() { return null; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Next") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameDeconstructCausesConflictInDeconstructionAssignment(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { {|deconstructconflict:var (y1, y2)|} = this; } public void [|$$Deconstruct|](out int x1, out int x2) { x1 = 1; x2 = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Deconstruct2") result.AssertLabeledSpansAre("deconstructconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameDeconstructCausesConflictInDeconstructionForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { foreach({|deconstructconflict:var (y1, y2)|} in new[] { this }) { } } public void [|$$Deconstruct|](out int x1, out int x2) { x1 = 1; x2 = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Deconstruct2") result.AssertLabeledSpansAre("deconstructconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameGetAwaiterCausesConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Threading.Tasks; using System.Runtime.CompilerServices; public class C { public TaskAwaiter<bool> [|Get$$Awaiter|]() => Task.FromResult(true).GetAwaiter(); static async void M(C c) { {|awaitconflict:await|} c; } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="GetAwaiter2") result.AssertLabeledSpansAre("awaitconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextInVBCausesConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Option Infer On Imports System Public Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Public Class C Public Function GetEnumerator() As B Return Nothing End Function End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class D { static void Main() { foreach (var x in {|foreachconflict:new C()|}) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="MovNext") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextInVBToUpperCaseOnlyCausesConflictInCSForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Option Infer On Imports System Public Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Public Class C Public Function GetEnumerator() As B Return Nothing End Function End Class Public Class E Public Sub Goo for each x in new C() next End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class D { static void Main() { foreach (var x in {|foreachconflict:new C()|}) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="MoveNEXT") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using 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.Remote.Testing Imports Microsoft.CodeAnalysis.Rename.ConflictEngine Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename.CSharp <[UseExportProvider]> Public Class ImplicitReferenceConflictTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextCausesConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class B { public int Current { get; set; } public bool [|$$MoveNext|]() { return false; } } class C { static void Main() { foreach (var x in {|foreachconflict:new C()|}) { } } public B GetEnumerator() { return null; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Next") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameDeconstructCausesConflictInDeconstructionAssignment(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { {|deconstructconflict:var (y1, y2)|} = this; } public void [|$$Deconstruct|](out int x1, out int x2) { x1 = 1; x2 = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Deconstruct2") result.AssertLabeledSpansAre("deconstructconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameDeconstructCausesConflictInDeconstructionForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void M() { foreach({|deconstructconflict:var (y1, y2)|} in new[] { this }) { } } public void [|$$Deconstruct|](out int x1, out int x2) { x1 = 1; x2 = 2; } } </Document> </Project> </Workspace>, host:=host, renameTo:="Deconstruct2") result.AssertLabeledSpansAre("deconstructconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameGetAwaiterCausesConflict(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Threading.Tasks; using System.Runtime.CompilerServices; public class C { public TaskAwaiter<bool> [|Get$$Awaiter|]() => Task.FromResult(true).GetAwaiter(); static async void M(C c) { {|awaitconflict:await|} c; } } ]]></Document> </Project> </Workspace>, host:=host, renameTo:="GetAwaiter2") result.AssertLabeledSpansAre("awaitconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextInVBCausesConflictInForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Option Infer On Imports System Public Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Public Class C Public Function GetEnumerator() As B Return Nothing End Function End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class D { static void Main() { foreach (var x in {|foreachconflict:new C()|}) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="MovNext") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub <WorkItem(528966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528966")> <Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameMoveNextInVBToUpperCaseOnlyCausesConflictInCSForEach(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="Visual Basic" AssemblyName="Project1" CommonReferences="true"> <Document> Option Infer On Imports System Public Class B Public Property Current As Integer Public Function [|$$MoveNext|]() As Boolean Return False End Function End Class Public Class C Public Function GetEnumerator() As B Return Nothing End Function End Class Public Class E Public Sub Goo for each x in new C() next End Sub End Class </Document> </Project> <Project Language="C#" AssemblyName="Project2" CommonReferences="true"> <ProjectReference>Project1</ProjectReference> <Document> class D { static void Main() { foreach (var x in {|foreachconflict:new C()|}) { } } } </Document> </Project> </Workspace>, host:=host, renameTo:="MoveNEXT") result.AssertLabeledSpansAre("foreachconflict", type:=RelatedLocationType.UnresolvedConflict) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/Core/Portable/Classification/SyntaxClassification/AbstractSyntaxClassifier.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 Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal abstract class AbstractSyntaxClassifier : ISyntaxClassifier { protected AbstractSyntaxClassifier() { } protected static string? GetClassificationForType(ITypeSymbol type) => type.GetClassification(); public virtual void AddClassifications(Workspace workspace, SyntaxNode syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { } public virtual void AddClassifications(Workspace workspace, SyntaxToken syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { } public virtual ImmutableArray<Type> SyntaxNodeTypes => ImmutableArray<Type>.Empty; public virtual ImmutableArray<int> SyntaxTokenKinds => ImmutableArray<int>.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. using System; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.Classification.Classifiers { internal abstract class AbstractSyntaxClassifier : ISyntaxClassifier { protected AbstractSyntaxClassifier() { } protected static string? GetClassificationForType(ITypeSymbol type) => type.GetClassification(); public virtual void AddClassifications(Workspace workspace, SyntaxNode syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { } public virtual void AddClassifications(Workspace workspace, SyntaxToken syntax, SemanticModel semanticModel, ArrayBuilder<ClassifiedSpan> result, CancellationToken cancellationToken) { } public virtual ImmutableArray<Type> SyntaxNodeTypes => ImmutableArray<Type>.Empty; public virtual ImmutableArray<int> SyntaxTokenKinds => ImmutableArray<int>.Empty; } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/VisualBasic/Impl/Options/IntelliSenseOptionPage.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 Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options <Guid(Guids.VisualBasicOptionPageIntelliSenseIdString)> Friend Class IntelliSenseOptionPage Inherits AbstractOptionPage Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Return New IntelliSenseOptionPageControl(optionStore) 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 Imports System.Runtime.InteropServices Imports Microsoft.VisualStudio.LanguageServices.Implementation.Options Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options <Guid(Guids.VisualBasicOptionPageIntelliSenseIdString)> Friend Class IntelliSenseOptionPage Inherits AbstractOptionPage Protected Overrides Function CreateOptionPage(serviceProvider As IServiceProvider, optionStore As OptionStore) As AbstractOptionPageControl Return New IntelliSenseOptionPageControl(optionStore) End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Core/Test/CodeModel/CSharp/ExternalCodePropertyTests.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.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class ExternalCodePropertyTests Inherits AbstractCodePropertyTests #Region "OverrideKind tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_None() Dim code = <Code> class C { public int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> abstract class C { public abstract int $$P { get; set; } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> class C { public virtual int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> abstract class B { public abstract int P { get; set; } } class C : B { public override int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> abstract class B { public abstract int P { get; set; } } class C : B { public override sealed int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub #End Region #Region "Parameter name tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters() Dim code = <Code> class Program { public int $$this[int x, int y] { get { return x * y; } set { } } } </Code> TestAllParameterNames(code, "x", "y") End Sub #End Region #Region "ReadWrite tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_GetSet() Dim code = <Code> class C { public int $$P { get { return default(int); } set { } } } </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Get() Dim code = <Code> class C { public int $$P { get { return default(int); } } } </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Set() Dim code = <Code> class C { public int $$P { set { } } } </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly) End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.CSharp Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True 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.Test.Utilities Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.CSharp Public Class ExternalCodePropertyTests Inherits AbstractCodePropertyTests #Region "OverrideKind tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_None() Dim code = <Code> class C { public int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindNone) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Abstract() Dim code = <Code> abstract class C { public abstract int $$P { get; set; } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindAbstract) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Virtual() Dim code = <Code> class C { public virtual int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindVirtual) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Override() Dim code = <Code> abstract class B { public abstract int P { get; set; } } class C : B { public override int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestOverrideKind_Sealed() Dim code = <Code> abstract class B { public abstract int P { get; set; } } class C : B { public override sealed int $$P { get { return default(int); } set { } } } </Code> TestOverrideKind(code, EnvDTE80.vsCMOverrideKind.vsCMOverrideKindOverride Or EnvDTE80.vsCMOverrideKind.vsCMOverrideKindSealed) End Sub #End Region #Region "Parameter name tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestParameterNameWithEscapeCharacters() Dim code = <Code> class Program { public int $$this[int x, int y] { get { return x * y; } set { } } } </Code> TestAllParameterNames(code, "x", "y") End Sub #End Region #Region "ReadWrite tests" <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_GetSet() Dim code = <Code> class C { public int $$P { get { return default(int); } set { } } } </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadWrite) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Get() Dim code = <Code> class C { public int $$P { get { return default(int); } } } </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindReadOnly) End Sub <WorkItem(9646, "https://github.com/dotnet/roslyn/issues/9646")> <WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)> Public Sub TestReadWrite_Set() Dim code = <Code> class C { public int $$P { set { } } } </Code> TestReadWrite(code, EnvDTE80.vsCMPropertyKind.vsCMPropertyKindWriteOnly) End Sub #End Region Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.CSharp Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Test2/Simplification/SimplifierAPITests.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.CSharp Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification <UseExportProvider> Public Class SimplifierAPITests <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestExpandAsync() As Task Await Assert.ThrowsAsync(Of ArgumentNullException)("node", Function() Return Simplifier.ExpandAsync(Of SyntaxNode)(Nothing, Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestExpandAsync2() As Task Dim node = GetSyntaxNode() Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() As Task Return Simplifier.ExpandAsync(node, Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestExpand() Assert.Throws(Of ArgumentNullException)("node", Sub() Simplifier.Expand(Of SyntaxNode)(Nothing, Nothing, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestExpand2() Dim node = GetSyntaxNode() Assert.Throws(Of ArgumentNullException)("semanticModel", Sub() Simplifier.Expand(node, Nothing, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestExpand3() Dim node = GetSyntaxNode() Dim semanticModel = GetSemanticModel() Assert.Throws(Of ArgumentNullException)("workspace", Sub() Simplifier.Expand(node, semanticModel, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestTokenExpandAsync() As Task Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ExpandAsync(Nothing, Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestTokenExpand() Assert.Throws(Of ArgumentNullException)("semanticModel", Sub() Dim expandedNode = Simplifier.Expand(Nothing, Nothing, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestTokenExpand2() Dim semanticModel = GetSemanticModel() Assert.Throws(Of ArgumentNullException)("workspace", Sub() Dim expandedNode = Simplifier.Expand(Nothing, semanticModel, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync() As Task Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync2() As Task Dim syntaxAnnotation As SyntaxAnnotation = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing, syntaxAnnotation) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync3() As Task Dim syntaxAnnotation As SyntaxAnnotation = Nothing Dim document = GetDocument() Await Assert.ThrowsAsync(Of ArgumentNullException)("annotation", Function() Return Simplifier.ReduceAsync(document, syntaxAnnotation) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync4() As Task Dim textSpan As TextSpan = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing, textSpan) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync5() As Task Dim spans As IEnumerable(Of TextSpan) = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing, spans) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync6() As Task Dim document = GetDocument() Dim spans As IEnumerable(Of TextSpan) = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("spans", Function() As Task Return Simplifier.ReduceAsync(document, spans) End Function) End Function Private Shared Function GetDocument() As Document Dim workspace = New AdhocWorkspace() Dim solution = workspace.CreateSolution(SolutionId.CreateNewId()) Dim project = workspace.AddProject("CSharpTest", LanguageNames.CSharp) Return workspace.AddDocument(project.Id, "CSharpFile.cs", SourceText.From("class C { }")) End Function Private Shared Function GetSemanticModel() As SemanticModel Return GetDocument().GetSemanticModelAsync().Result End Function Private Shared Function GetSyntaxNode() As SyntaxNode Return SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("Test")) 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.CSharp Imports Microsoft.CodeAnalysis.Simplification Imports Microsoft.CodeAnalysis.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification <UseExportProvider> Public Class SimplifierAPITests <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestExpandAsync() As Task Await Assert.ThrowsAsync(Of ArgumentNullException)("node", Function() Return Simplifier.ExpandAsync(Of SyntaxNode)(Nothing, Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestExpandAsync2() As Task Dim node = GetSyntaxNode() Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() As Task Return Simplifier.ExpandAsync(node, Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestExpand() Assert.Throws(Of ArgumentNullException)("node", Sub() Simplifier.Expand(Of SyntaxNode)(Nothing, Nothing, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestExpand2() Dim node = GetSyntaxNode() Assert.Throws(Of ArgumentNullException)("semanticModel", Sub() Simplifier.Expand(node, Nothing, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestExpand3() Dim node = GetSyntaxNode() Dim semanticModel = GetSemanticModel() Assert.Throws(Of ArgumentNullException)("workspace", Sub() Simplifier.Expand(node, semanticModel, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestTokenExpandAsync() As Task Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ExpandAsync(Nothing, Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestTokenExpand() Assert.Throws(Of ArgumentNullException)("semanticModel", Sub() Dim expandedNode = Simplifier.Expand(Nothing, Nothing, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Sub TestTokenExpand2() Dim semanticModel = GetSemanticModel() Assert.Throws(Of ArgumentNullException)("workspace", Sub() Dim expandedNode = Simplifier.Expand(Nothing, semanticModel, Nothing) End Sub) End Sub <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync() As Task Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync2() As Task Dim syntaxAnnotation As SyntaxAnnotation = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing, syntaxAnnotation) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync3() As Task Dim syntaxAnnotation As SyntaxAnnotation = Nothing Dim document = GetDocument() Await Assert.ThrowsAsync(Of ArgumentNullException)("annotation", Function() Return Simplifier.ReduceAsync(document, syntaxAnnotation) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync4() As Task Dim textSpan As TextSpan = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing, textSpan) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync5() As Task Dim spans As IEnumerable(Of TextSpan) = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("document", Function() Return Simplifier.ReduceAsync(Nothing, spans) End Function) End Function <Fact, Trait(Traits.Feature, Traits.Features.Simplification)> Public Async Function TestReduceAsync6() As Task Dim document = GetDocument() Dim spans As IEnumerable(Of TextSpan) = Nothing Await Assert.ThrowsAsync(Of ArgumentNullException)("spans", Function() As Task Return Simplifier.ReduceAsync(document, spans) End Function) End Function Private Shared Function GetDocument() As Document Dim workspace = New AdhocWorkspace() Dim solution = workspace.CreateSolution(SolutionId.CreateNewId()) Dim project = workspace.AddProject("CSharpTest", LanguageNames.CSharp) Return workspace.AddDocument(project.Id, "CSharpFile.cs", SourceText.From("class C { }")) End Function Private Shared Function GetSemanticModel() As SemanticModel Return GetDocument().GetSemanticModelAsync().Result End Function Private Shared Function GetSyntaxNode() As SyntaxNode Return SyntaxFactory.IdentifierName(SyntaxFactory.Identifier("Test")) End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Core/Def/Progression/GraphNodeCreation.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 System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.LanguageServices.Implementation.Progression; namespace Microsoft.VisualStudio.LanguageServices.Progression { /// <summary> /// A helper class that implements the creation of <see cref="GraphNode"/>s. /// </summary> public static class GraphNodeCreation { public static async Task<GraphNodeId> CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) { if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (solution == null) { throw new ArgumentNullException(nameof(solution)); } switch (symbol.Kind) { case SymbolKind.Assembly: return await GraphNodeIdCreation.GetIdForAssemblyAsync((IAssemblySymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Namespace: return await GraphNodeIdCreation.GetIdForNamespaceAsync((INamespaceSymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.NamedType: return await GraphNodeIdCreation.GetIdForTypeAsync((ITypeSymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Method: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return await GraphNodeIdCreation.GetIdForMemberAsync(symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Parameter: return await GraphNodeIdCreation.GetIdForParameterAsync((IParameterSymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Local: case SymbolKind.RangeVariable: return await GraphNodeIdCreation.GetIdForLocalVariableAsync(symbol, solution, cancellationToken).ConfigureAwait(false); default: throw new ArgumentException(string.Format(ServicesVSResources.Can_t_create_a_node_id_for_this_symbol_kind_colon_0, symbol)); } } public static async Task<GraphNode> CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken) { if (graph == null) { throw new ArgumentNullException(nameof(graph)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (solution == null) { throw new ArgumentNullException(nameof(solution)); } return await GraphBuilder.GetOrCreateNodeAsync(graph, symbol, solution, cancellationToken).ConfigureAwait(false); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.LanguageServices.Implementation.Progression; namespace Microsoft.VisualStudio.LanguageServices.Progression { /// <summary> /// A helper class that implements the creation of <see cref="GraphNode"/>s. /// </summary> public static class GraphNodeCreation { public static async Task<GraphNodeId> CreateNodeIdAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken) { if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (solution == null) { throw new ArgumentNullException(nameof(solution)); } switch (symbol.Kind) { case SymbolKind.Assembly: return await GraphNodeIdCreation.GetIdForAssemblyAsync((IAssemblySymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Namespace: return await GraphNodeIdCreation.GetIdForNamespaceAsync((INamespaceSymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.NamedType: return await GraphNodeIdCreation.GetIdForTypeAsync((ITypeSymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Method: case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: return await GraphNodeIdCreation.GetIdForMemberAsync(symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Parameter: return await GraphNodeIdCreation.GetIdForParameterAsync((IParameterSymbol)symbol, solution, cancellationToken).ConfigureAwait(false); case SymbolKind.Local: case SymbolKind.RangeVariable: return await GraphNodeIdCreation.GetIdForLocalVariableAsync(symbol, solution, cancellationToken).ConfigureAwait(false); default: throw new ArgumentException(string.Format(ServicesVSResources.Can_t_create_a_node_id_for_this_symbol_kind_colon_0, symbol)); } } public static async Task<GraphNode> CreateNodeAsync(this Graph graph, ISymbol symbol, Solution solution, CancellationToken cancellationToken) { if (graph == null) { throw new ArgumentNullException(nameof(graph)); } if (symbol == null) { throw new ArgumentNullException(nameof(symbol)); } if (solution == null) { throw new ArgumentNullException(nameof(solution)); } return await GraphBuilder.GetOrCreateNodeAsync(graph, symbol, solution, cancellationToken).ConfigureAwait(false); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Options/OptionGroup.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Group/sub-feature associated with an option. /// </summary> internal sealed class OptionGroup { public static readonly OptionGroup Default = new(string.Empty, int.MaxValue); public OptionGroup(string description, int priority) { Description = description ?? throw new ArgumentNullException(nameof(description)); Priority = priority; } /// <summary> /// A localizable resource description string for the option group. /// </summary> public string Description { get; } /// <summary> /// Relative priority of the option group with respect to other option groups within the same feature. /// </summary> public int Priority { 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; namespace Microsoft.CodeAnalysis.Options { /// <summary> /// Group/sub-feature associated with an option. /// </summary> internal sealed class OptionGroup { public static readonly OptionGroup Default = new(string.Empty, int.MaxValue); public OptionGroup(string description, int priority) { Description = description ?? throw new ArgumentNullException(nameof(description)); Priority = priority; } /// <summary> /// A localizable resource description string for the option group. /// </summary> public string Description { get; } /// <summary> /// Relative priority of the option group with respect to other option groups within the same feature. /// </summary> public int Priority { get; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/Core/CodeAnalysisTest/Collections/List/SegmentedList.Generic.Tests.ConvertAll.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.ConvertAll.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Fact] public void ConvertAll() { var list = new SegmentedList<int>(new int[] { 1, 2, 3 }); var before = list.ToSegmentedList(); var after = list.ConvertAll((i) => { return 10 * i; }); Assert.Equal(before.Count, list.Count); Assert.Equal(before.Count, after.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(before[i], list[i]); Assert.Equal(before[i] * 10, after[i]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // NOTE: This code is derived from an implementation originally in dotnet/runtime: // https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/System.Collections/tests/Generic/List/List.Generic.Tests.ConvertAll.cs // // See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the // reference implementation. using System.Linq; using Microsoft.CodeAnalysis.Collections; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public abstract partial class SegmentedList_Generic_Tests<T> : IList_Generic_Tests<T> { [Fact] public void ConvertAll() { var list = new SegmentedList<int>(new int[] { 1, 2, 3 }); var before = list.ToSegmentedList(); var after = list.ConvertAll((i) => { return 10 * i; }); Assert.Equal(before.Count, list.Count); Assert.Equal(before.Count, after.Count); for (int i = 0; i < list.Count; i++) { Assert.Equal(before[i], list[i]); Assert.Equal(before[i] * 10, after[i]); } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/Core/Portable/SolutionCrawler/InvocationReasons.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; using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial struct InvocationReasons : IEnumerable<string> { public static readonly InvocationReasons Empty = new(ImmutableHashSet<string>.Empty); private readonly ImmutableHashSet<string> _reasons; public InvocationReasons(string reason) : this(ImmutableHashSet.Create<string>(reason)) { } private InvocationReasons(ImmutableHashSet<string> reasons) => _reasons = reasons; public bool Contains(string reason) => _reasons.Contains(reason); public InvocationReasons With(InvocationReasons invocationReasons) => new((_reasons ?? ImmutableHashSet<string>.Empty).Union(invocationReasons._reasons)); public InvocationReasons With(string reason) => new((_reasons ?? ImmutableHashSet<string>.Empty).Add(reason)); public bool IsEmpty { get { return _reasons == null || _reasons.Count == 0; } } public ImmutableHashSet<string>.Enumerator GetEnumerator() => _reasons.GetEnumerator(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => _reasons.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _reasons.GetEnumerator(); public override string ToString() => string.Join("|", _reasons ?? ImmutableHashSet<string>.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; using System.Collections.Generic; using System.Collections.Immutable; namespace Microsoft.CodeAnalysis.SolutionCrawler { internal partial struct InvocationReasons : IEnumerable<string> { public static readonly InvocationReasons Empty = new(ImmutableHashSet<string>.Empty); private readonly ImmutableHashSet<string> _reasons; public InvocationReasons(string reason) : this(ImmutableHashSet.Create<string>(reason)) { } private InvocationReasons(ImmutableHashSet<string> reasons) => _reasons = reasons; public bool Contains(string reason) => _reasons.Contains(reason); public InvocationReasons With(InvocationReasons invocationReasons) => new((_reasons ?? ImmutableHashSet<string>.Empty).Union(invocationReasons._reasons)); public InvocationReasons With(string reason) => new((_reasons ?? ImmutableHashSet<string>.Empty).Add(reason)); public bool IsEmpty { get { return _reasons == null || _reasons.Count == 0; } } public ImmutableHashSet<string>.Enumerator GetEnumerator() => _reasons.GetEnumerator(); IEnumerator<string> IEnumerable<string>.GetEnumerator() => _reasons.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => _reasons.GetEnumerator(); public override string ToString() => string.Join("|", _reasons ?? ImmutableHashSet<string>.Empty); } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/IntegrationTest/IntegrationTests/VisualBasic/BasicKeywordHighlighting.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; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicKeywordHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicKeywordHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicKeywordHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void NavigationBetweenKeywords() { VisualStudio.Editor.SetText(@" Class C Sub Main() For a = 0 To 1 Step 1 For b = 0 To 2 Next b, a End Sub End Class"); Verify("To", 4); VisualStudio.Editor.InvokeNavigateToNextHighlightedReference(); VisualStudio.Editor.Verify.CurrentLineText("For a = 0 To 1 Step$$ 1", assertCaretPosition: true, trimWhitespace: true); } private void Verify(string marker, int expectedCount) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.KeywordHighlighting); Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags().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. using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Roslyn.VisualStudio.IntegrationTests.VisualBasic { [Collection(nameof(SharedIntegrationHostFixture))] public class BasicKeywordHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.VisualBasic; public BasicKeywordHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(BasicKeywordHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void NavigationBetweenKeywords() { VisualStudio.Editor.SetText(@" Class C Sub Main() For a = 0 To 1 Step 1 For b = 0 To 2 Next b, a End Sub End Class"); Verify("To", 4); VisualStudio.Editor.InvokeNavigateToNextHighlightedReference(); VisualStudio.Editor.Verify.CurrentLineText("For a = 0 To 1 Step$$ 1", assertCaretPosition: true, trimWhitespace: true); } private void Verify(string marker, int expectedCount) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.KeywordHighlighting); Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags().Length); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/Core/Portable/Workspace/Solution/ProjectDependencyGraph_RemoveProject.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class ProjectDependencyGraph { internal ProjectDependencyGraph WithProjectRemoved(ProjectId projectId) { Contract.ThrowIfFalse(_projectIds.Contains(projectId)); // Project ID set and direct forward references are trivially updated by removing the key corresponding to // the project getting removed. var projectIds = _projectIds.Remove(projectId); var referencesMap = ComputeNewReferencesMapForRemovedProject( existingForwardReferencesMap: _referencesMap, existingReverseReferencesMap: _lazyReverseReferencesMap, projectId); // The direct reverse references map is updated by removing the key for the project getting removed, and // also updating any direct references to the removed project. var reverseReferencesMap = ComputeNewReverseReferencesMapForRemovedProject( existingForwardReferencesMap: _referencesMap, existingReverseReferencesMap: _lazyReverseReferencesMap, projectId); var transitiveReferencesMap = ComputeNewTransitiveReferencesMapForRemovedProject(_transitiveReferencesMap, projectId); var reverseTransitiveReferencesMap = ComputeNewReverseTransitiveReferencesMapForRemovedProject(_reverseTransitiveReferencesMap, projectId); return new ProjectDependencyGraph( projectIds, referencesMap, reverseReferencesMap, transitiveReferencesMap, reverseTransitiveReferencesMap, topologicallySortedProjects: default, dependencySets: default); } /// <summary> /// Computes a new <see cref="_referencesMap"/> for the removal of a project. /// </summary> /// <param name="existingForwardReferencesMap">The <see cref="_referencesMap"/> prior to the removal.</param> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal. /// This map serves as a hint to the removal process; i.e. it is assumed correct if it contains data, but may be /// omitted without impacting correctness.</param> /// <param name="removedProjectId">The ID of the project which is being removed.</param> /// <returns>The <see cref="_referencesMap"/> for the project dependency graph once the project is removed.</returns> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId removedProjectId) { var builder = existingForwardReferencesMap.ToBuilder(); if (existingReverseReferencesMap is object) { // We know all the projects directly referencing 'projectId', so remove 'projectId' from the set of // references in each of those cases directly. if (existingReverseReferencesMap.TryGetValue(removedProjectId, out var referencingProjects)) { foreach (var id in referencingProjects) { builder.MultiRemove(id, removedProjectId); } } } else { // We don't know which projects reference 'projectId', so iterate over all known projects and remove // 'projectId' from the set of references if it exists. foreach (var (id, _) in existingForwardReferencesMap) { builder.MultiRemove(id, removedProjectId); } } // Finally, remove 'projectId' itself. builder.Remove(removedProjectId); return builder.ToImmutable(); } /// <summary> /// Computes a new <see cref="_lazyReverseReferencesMap"/> for the removal of a project. /// </summary> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal, /// or <see langword="null"/> if the value prior to removal was not computed for the graph.</param> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? ComputeNewReverseReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId removedProjectId) { if (existingReverseReferencesMap is null) { // The map was never calculated for the previous graph, so there is nothing to update. return null; } if (!existingForwardReferencesMap.TryGetValue(removedProjectId, out var forwardReferences)) { // The removed project did not reference any other projects, so we simply remove it. return existingReverseReferencesMap.Remove(removedProjectId); } var builder = existingReverseReferencesMap.ToBuilder(); // Iterate over each project referenced by 'removedProjectId', which is now being removed. Update the // reverse references map for the project to no longer include 'removedProjectId' in the list. foreach (var referencedProjectId in forwardReferences) { builder.MultiRemove(referencedProjectId, removedProjectId); } // Finally, remove 'removedProjectId' itself. builder.Remove(removedProjectId); return builder.ToImmutable(); } /// <summary> /// Computes a new <see cref="_transitiveReferencesMap"/> for the removal of a project. /// </summary> /// <seealso cref="ComputeNewReverseTransitiveReferencesMapForRemovedProject"/> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewTransitiveReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingTransitiveReferencesMap, ProjectId removedProjectId) { var builder = existingTransitiveReferencesMap.ToBuilder(); // Iterate over each project and invalidate the transitive references for the project if the project has an // existing transitive reference to 'removedProjectId'. foreach (var (project, references) in existingTransitiveReferencesMap) { if (references.Contains(removedProjectId)) { // The project transitively referenced 'removedProjectId', so any transitive references brought in // exclusively through this reference are no longer valid. Remove the project from the map and the // new transitive references will be recomputed the first time they are needed. builder.Remove(project); } } // Finally, remove 'projectId' itself. builder.Remove(removedProjectId); return builder.ToImmutable(); } /// <summary> /// Computes a new <see cref="_reverseTransitiveReferencesMap"/> for the removal of a project. /// </summary> /// <seealso cref="ComputeNewTransitiveReferencesMapForRemovedProject"/> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReverseTransitiveReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingReverseTransitiveReferencesMap, ProjectId removedProjectId) { var builder = existingReverseTransitiveReferencesMap.ToBuilder(); // Iterate over each project and invalidate the transitive reverse references for the project if the project // has an existing transitive reverse reference to 'removedProjectId'. foreach (var (project, references) in existingReverseTransitiveReferencesMap) { if (references.Contains(removedProjectId)) { // 'removedProjectId' transitively referenced the project, so any transitive reverse references // brought in exclusively through this reverse reference are no longer valid. Remove the project // from the map and the new transitive reverse references will be recomputed the first time they are // needed. builder.Remove(project); } } builder.Remove(removedProjectId); return builder.ToImmutable(); } } }
// Licensed to the .NET Foundation under one or more 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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis { public partial class ProjectDependencyGraph { internal ProjectDependencyGraph WithProjectRemoved(ProjectId projectId) { Contract.ThrowIfFalse(_projectIds.Contains(projectId)); // Project ID set and direct forward references are trivially updated by removing the key corresponding to // the project getting removed. var projectIds = _projectIds.Remove(projectId); var referencesMap = ComputeNewReferencesMapForRemovedProject( existingForwardReferencesMap: _referencesMap, existingReverseReferencesMap: _lazyReverseReferencesMap, projectId); // The direct reverse references map is updated by removing the key for the project getting removed, and // also updating any direct references to the removed project. var reverseReferencesMap = ComputeNewReverseReferencesMapForRemovedProject( existingForwardReferencesMap: _referencesMap, existingReverseReferencesMap: _lazyReverseReferencesMap, projectId); var transitiveReferencesMap = ComputeNewTransitiveReferencesMapForRemovedProject(_transitiveReferencesMap, projectId); var reverseTransitiveReferencesMap = ComputeNewReverseTransitiveReferencesMapForRemovedProject(_reverseTransitiveReferencesMap, projectId); return new ProjectDependencyGraph( projectIds, referencesMap, reverseReferencesMap, transitiveReferencesMap, reverseTransitiveReferencesMap, topologicallySortedProjects: default, dependencySets: default); } /// <summary> /// Computes a new <see cref="_referencesMap"/> for the removal of a project. /// </summary> /// <param name="existingForwardReferencesMap">The <see cref="_referencesMap"/> prior to the removal.</param> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal. /// This map serves as a hint to the removal process; i.e. it is assumed correct if it contains data, but may be /// omitted without impacting correctness.</param> /// <param name="removedProjectId">The ID of the project which is being removed.</param> /// <returns>The <see cref="_referencesMap"/> for the project dependency graph once the project is removed.</returns> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId removedProjectId) { var builder = existingForwardReferencesMap.ToBuilder(); if (existingReverseReferencesMap is object) { // We know all the projects directly referencing 'projectId', so remove 'projectId' from the set of // references in each of those cases directly. if (existingReverseReferencesMap.TryGetValue(removedProjectId, out var referencingProjects)) { foreach (var id in referencingProjects) { builder.MultiRemove(id, removedProjectId); } } } else { // We don't know which projects reference 'projectId', so iterate over all known projects and remove // 'projectId' from the set of references if it exists. foreach (var (id, _) in existingForwardReferencesMap) { builder.MultiRemove(id, removedProjectId); } } // Finally, remove 'projectId' itself. builder.Remove(removedProjectId); return builder.ToImmutable(); } /// <summary> /// Computes a new <see cref="_lazyReverseReferencesMap"/> for the removal of a project. /// </summary> /// <param name="existingReverseReferencesMap">The <see cref="_lazyReverseReferencesMap"/> prior to the removal, /// or <see langword="null"/> if the value prior to removal was not computed for the graph.</param> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? ComputeNewReverseReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingForwardReferencesMap, ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>>? existingReverseReferencesMap, ProjectId removedProjectId) { if (existingReverseReferencesMap is null) { // The map was never calculated for the previous graph, so there is nothing to update. return null; } if (!existingForwardReferencesMap.TryGetValue(removedProjectId, out var forwardReferences)) { // The removed project did not reference any other projects, so we simply remove it. return existingReverseReferencesMap.Remove(removedProjectId); } var builder = existingReverseReferencesMap.ToBuilder(); // Iterate over each project referenced by 'removedProjectId', which is now being removed. Update the // reverse references map for the project to no longer include 'removedProjectId' in the list. foreach (var referencedProjectId in forwardReferences) { builder.MultiRemove(referencedProjectId, removedProjectId); } // Finally, remove 'removedProjectId' itself. builder.Remove(removedProjectId); return builder.ToImmutable(); } /// <summary> /// Computes a new <see cref="_transitiveReferencesMap"/> for the removal of a project. /// </summary> /// <seealso cref="ComputeNewReverseTransitiveReferencesMapForRemovedProject"/> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewTransitiveReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingTransitiveReferencesMap, ProjectId removedProjectId) { var builder = existingTransitiveReferencesMap.ToBuilder(); // Iterate over each project and invalidate the transitive references for the project if the project has an // existing transitive reference to 'removedProjectId'. foreach (var (project, references) in existingTransitiveReferencesMap) { if (references.Contains(removedProjectId)) { // The project transitively referenced 'removedProjectId', so any transitive references brought in // exclusively through this reference are no longer valid. Remove the project from the map and the // new transitive references will be recomputed the first time they are needed. builder.Remove(project); } } // Finally, remove 'projectId' itself. builder.Remove(removedProjectId); return builder.ToImmutable(); } /// <summary> /// Computes a new <see cref="_reverseTransitiveReferencesMap"/> for the removal of a project. /// </summary> /// <seealso cref="ComputeNewTransitiveReferencesMapForRemovedProject"/> private static ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> ComputeNewReverseTransitiveReferencesMapForRemovedProject( ImmutableDictionary<ProjectId, ImmutableHashSet<ProjectId>> existingReverseTransitiveReferencesMap, ProjectId removedProjectId) { var builder = existingReverseTransitiveReferencesMap.ToBuilder(); // Iterate over each project and invalidate the transitive reverse references for the project if the project // has an existing transitive reverse reference to 'removedProjectId'. foreach (var (project, references) in existingReverseTransitiveReferencesMap) { if (references.Contains(removedProjectId)) { // 'removedProjectId' transitively referenced the project, so any transitive reverse references // brought in exclusively through this reverse reference are no longer valid. Remove the project // from the map and the new transitive reverse references will be recomputed the first time they are // needed. builder.Remove(project); } } builder.Remove(removedProjectId); return builder.ToImmutable(); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/CSharp/Portable/ConvertLinq/ConvertForEachToLinqQuery/AbstractConverter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { internal abstract class AbstractConverter : IConverter<ForEachStatementSyntax, StatementSyntax> { public ForEachInfo<ForEachStatementSyntax, StatementSyntax> ForEachInfo { get; } public AbstractConverter(ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo) => ForEachInfo = forEachInfo; public abstract void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken); /// <summary> /// Creates a query expression or a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used into the last Select in the query expression or linq invocation.</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <param name="convertToQuery">Flag indicating if a query expression should be generated</param> /// <returns></returns> protected ExpressionSyntax CreateQueryExpressionOrLinqInvocation( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect, bool convertToQuery) { return convertToQuery ? CreateQueryExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect) : (ExpressionSyntax)CreateLinqInvocationOrSimpleExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect); } /// <summary> /// Creates a query expression. /// </summary> /// <param name="selectExpression">expression to be used into the last 'select ...' in the query expression</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private QueryExpressionSyntax CreateQueryExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) => SyntaxFactory.QueryExpression( CreateFromClause(ForEachInfo.ForEachStatement, ForEachInfo.LeadingTokens.GetTrivia(), Enumerable.Empty<SyntaxTrivia>()), SyntaxFactory.QueryBody( SyntaxFactory.List(ForEachInfo.ConvertingExtendedNodes.Select(node => CreateQueryClause(node))), SyntaxFactory.SelectClause(selectExpression) .WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)), continuation: null)) // The current coverage of foreach statements to support does not need to use query continuations. .WithAdditionalAnnotations(Formatter.Annotation); private static QueryClauseSyntax CreateQueryClause(ExtendedSyntaxNode node) { switch (node.Node.Kind()) { case SyntaxKind.VariableDeclarator: var variable = (VariableDeclaratorSyntax)node.Node; return SyntaxFactory.LetClause( SyntaxFactory.Token(SyntaxKind.LetKeyword), variable.Identifier, variable.Initializer.EqualsToken, variable.Initializer.Value) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.ForEachStatement: return CreateFromClause((ForEachStatementSyntax)node.Node, node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; return SyntaxFactory.WhereClause( SyntaxFactory.Token(SyntaxKind.WhereKeyword) .WithCommentsFrom(ifStatement.IfKeyword.LeadingTrivia, ifStatement.IfKeyword.TrailingTrivia), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); } throw ExceptionUtilities.Unreachable; } private static FromClauseSyntax CreateFromClause( ForEachStatementSyntax forEachStatement, IEnumerable<SyntaxTrivia> extraLeadingTrivia, IEnumerable<SyntaxTrivia> extraTrailingTrivia) => SyntaxFactory.FromClause( fromKeyword: SyntaxFactory.Token(SyntaxKind.FromKeyword) .WithCommentsFrom( forEachStatement.ForEachKeyword.LeadingTrivia, forEachStatement.ForEachKeyword.TrailingTrivia, forEachStatement.OpenParenToken) .KeepCommentsAndAddElasticMarkers(), type: forEachStatement.Type.IsVar ? null : forEachStatement.Type, identifier: forEachStatement.Type.IsVar ? forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false)) : forEachStatement.Identifier, inKeyword: forEachStatement.InKeyword.KeepCommentsAndAddElasticMarkers(), expression: forEachStatement.Expression) .WithCommentsFrom(extraLeadingTrivia, extraTrailingTrivia, forEachStatement.CloseParenToken); /// <summary> /// Creates a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used in the last 'Select' invocation</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) { var foreachStatement = ForEachInfo.ForEachStatement; selectExpression = selectExpression.WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)); var currentExtendedNodeIndex = 0; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: ForEachInfo.LeadingTokens.GetTrivia(), trailingCommentsTrivia: Enumerable.Empty<SyntaxTrivia>(), currentExtendedNodeIndex: ref currentExtendedNodeIndex) .WithAdditionalAnnotations(Formatter.Annotation); } private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ForEachStatementSyntax forEachStatement, ExpressionSyntax receiverForInvocation, IEnumerable<SyntaxTrivia> leadingCommentsTrivia, IEnumerable<SyntaxTrivia> trailingCommentsTrivia, ExpressionSyntax selectExpression, ref int currentExtendedNodeIndex) { leadingCommentsTrivia = forEachStatement.ForEachKeyword.GetAllTrivia().Concat(leadingCommentsTrivia); // Recursively create linq invocations, possibly updating the receiver (Where invocations), to get the inner expression for // the lambda body for the linq invocation to be created for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // if (n1 > n2) // yield return n1 + n2; // // OUTPUT: // c1.SelectMany(n1 => c2.Where(n2 => n1 > n2).Select(n2 => n1 + n2)) // var hasForEachChild = false; var lambdaBody = CreateLinqInvocationForExtendedNode(selectExpression, ref currentExtendedNodeIndex, ref receiverForInvocation, ref hasForEachChild); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false))), lambdaBody) .WithCommentsFrom(leadingCommentsTrivia, trailingCommentsTrivia, forEachStatement.OpenParenToken, forEachStatement.InKeyword, forEachStatement.CloseParenToken); // Create Select or SelectMany linq invocation for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // ... // // OUTPUT: // c1.Select(n1 => ... // OR // c1.SelectMany(n1 => ... // var invokedMethodName = !hasForEachChild ? nameof(Enumerable.Select) : nameof(Enumerable.SelectMany); // Avoid `.Select(x => x)` if (invokedMethodName == nameof(Enumerable.Select) && lambdaBody is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == forEachStatement.Identifier.ValueText) { // Because we're dropping the lambda, any comments associated with it need to be preserved. var droppedTrivia = new List<SyntaxTrivia>(); foreach (var token in lambda.DescendantTokens()) { droppedTrivia.AddRange(token.GetAllTrivia().Where(t => !t.IsWhitespace())); } return receiverForInvocation.WithAppendedTrailingTrivia(droppedTrivia); } return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiverForInvocation.Parenthesize(), SyntaxFactory.IdentifierName(invokedMethodName)), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); } /// <summary> /// Creates a linq invocation expression for the <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> node at the given index <paramref name="extendedNodeIndex"/> /// or returns the <paramref name="selectExpression"/> if all extended nodes have been processed. /// </summary> /// <param name="selectExpression">Innermost select expression</param> /// <param name="extendedNodeIndex">Index into <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> to be processed and updated.</param> /// <param name="receiver">Receiver for the generated linq invocation. Updated when processing an if statement.</param> /// <param name="hasForEachChild">Flag indicating if any of the processed <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> is a <see cref="ForEachStatementSyntax"/>.</param> private ExpressionSyntax CreateLinqInvocationForExtendedNode( ExpressionSyntax selectExpression, ref int extendedNodeIndex, ref ExpressionSyntax receiver, ref bool hasForEachChild) { // Check if we have converted all the descendant foreach/if statements. // If so, we return the select expression. if (extendedNodeIndex == ForEachInfo.ConvertingExtendedNodes.Length) { return selectExpression; } // Otherwise, convert the next foreach/if statement into a linq invocation. var node = ForEachInfo.ConvertingExtendedNodes[extendedNodeIndex]; switch (node.Node.Kind()) { // Nested ForEach statement is converted into a nested Select or SelectMany linq invocation. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // ... // // OUTPUT: // c1.SelectMany(n1 => c2.Select(n2 => ... // case SyntaxKind.ForEachStatement: hasForEachChild = true; var foreachStatement = (ForEachStatementSyntax)node.Node; ++extendedNodeIndex; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: node.ExtraLeadingComments, trailingCommentsTrivia: node.ExtraTrailingComments, currentExtendedNodeIndex: ref extendedNodeIndex); // Nested If statement is converted into a Where method invocation on the current receiver. For example: // // INPUT: // foreach (var n1 in c1) // if (n1 > 0) // ... // // OUTPUT: // c1.Where(n1 => n1 > 0).Select(n1 => ... // case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; var parentForEachStatement = ifStatement.GetAncestor<ForEachStatementSyntax>(); var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(ifStatement.IfKeyword.GetAllTrivia().Concat(node.ExtraLeadingComments), node.ExtraTrailingComments); receiver = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiver.Parenthesize(), SyntaxFactory.IdentifierName(nameof(Enumerable.Where))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); ++extendedNodeIndex; return CreateLinqInvocationForExtendedNode(selectExpression, ref extendedNodeIndex, ref receiver, ref hasForEachChild); } throw ExceptionUtilities.Unreachable; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.ConvertLinq.ConvertForEachToLinqQuery; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; using SyntaxNodeOrTokenExtensions = Microsoft.CodeAnalysis.Shared.Extensions.SyntaxNodeOrTokenExtensions; namespace Microsoft.CodeAnalysis.CSharp.ConvertLinq.ConvertForEachToLinqQuery { internal abstract class AbstractConverter : IConverter<ForEachStatementSyntax, StatementSyntax> { public ForEachInfo<ForEachStatementSyntax, StatementSyntax> ForEachInfo { get; } public AbstractConverter(ForEachInfo<ForEachStatementSyntax, StatementSyntax> forEachInfo) => ForEachInfo = forEachInfo; public abstract void Convert(SyntaxEditor editor, bool convertToQuery, CancellationToken cancellationToken); /// <summary> /// Creates a query expression or a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used into the last Select in the query expression or linq invocation.</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <param name="convertToQuery">Flag indicating if a query expression should be generated</param> /// <returns></returns> protected ExpressionSyntax CreateQueryExpressionOrLinqInvocation( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect, bool convertToQuery) { return convertToQuery ? CreateQueryExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect) : (ExpressionSyntax)CreateLinqInvocationOrSimpleExpression(selectExpression, leadingTokensForSelect, trailingTokensForSelect); } /// <summary> /// Creates a query expression. /// </summary> /// <param name="selectExpression">expression to be used into the last 'select ...' in the query expression</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private QueryExpressionSyntax CreateQueryExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) => SyntaxFactory.QueryExpression( CreateFromClause(ForEachInfo.ForEachStatement, ForEachInfo.LeadingTokens.GetTrivia(), Enumerable.Empty<SyntaxTrivia>()), SyntaxFactory.QueryBody( SyntaxFactory.List(ForEachInfo.ConvertingExtendedNodes.Select(node => CreateQueryClause(node))), SyntaxFactory.SelectClause(selectExpression) .WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)), continuation: null)) // The current coverage of foreach statements to support does not need to use query continuations. .WithAdditionalAnnotations(Formatter.Annotation); private static QueryClauseSyntax CreateQueryClause(ExtendedSyntaxNode node) { switch (node.Node.Kind()) { case SyntaxKind.VariableDeclarator: var variable = (VariableDeclaratorSyntax)node.Node; return SyntaxFactory.LetClause( SyntaxFactory.Token(SyntaxKind.LetKeyword), variable.Identifier, variable.Initializer.EqualsToken, variable.Initializer.Value) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.ForEachStatement: return CreateFromClause((ForEachStatementSyntax)node.Node, node.ExtraLeadingComments, node.ExtraTrailingComments); case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; return SyntaxFactory.WhereClause( SyntaxFactory.Token(SyntaxKind.WhereKeyword) .WithCommentsFrom(ifStatement.IfKeyword.LeadingTrivia, ifStatement.IfKeyword.TrailingTrivia), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(node.ExtraLeadingComments, node.ExtraTrailingComments); } throw ExceptionUtilities.Unreachable; } private static FromClauseSyntax CreateFromClause( ForEachStatementSyntax forEachStatement, IEnumerable<SyntaxTrivia> extraLeadingTrivia, IEnumerable<SyntaxTrivia> extraTrailingTrivia) => SyntaxFactory.FromClause( fromKeyword: SyntaxFactory.Token(SyntaxKind.FromKeyword) .WithCommentsFrom( forEachStatement.ForEachKeyword.LeadingTrivia, forEachStatement.ForEachKeyword.TrailingTrivia, forEachStatement.OpenParenToken) .KeepCommentsAndAddElasticMarkers(), type: forEachStatement.Type.IsVar ? null : forEachStatement.Type, identifier: forEachStatement.Type.IsVar ? forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false)) : forEachStatement.Identifier, inKeyword: forEachStatement.InKeyword.KeepCommentsAndAddElasticMarkers(), expression: forEachStatement.Expression) .WithCommentsFrom(extraLeadingTrivia, extraTrailingTrivia, forEachStatement.CloseParenToken); /// <summary> /// Creates a linq invocation expression. /// </summary> /// <param name="selectExpression">expression to be used in the last 'Select' invocation</param> /// <param name="leadingTokensForSelect">extra leading tokens to be added to the select clause</param> /// <param name="trailingTokensForSelect">extra trailing tokens to be added to the select clause</param> /// <returns></returns> private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ExpressionSyntax selectExpression, IEnumerable<SyntaxToken> leadingTokensForSelect, IEnumerable<SyntaxToken> trailingTokensForSelect) { var foreachStatement = ForEachInfo.ForEachStatement; selectExpression = selectExpression.WithCommentsFrom(leadingTokensForSelect, ForEachInfo.TrailingTokens.Concat(trailingTokensForSelect)); var currentExtendedNodeIndex = 0; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: ForEachInfo.LeadingTokens.GetTrivia(), trailingCommentsTrivia: Enumerable.Empty<SyntaxTrivia>(), currentExtendedNodeIndex: ref currentExtendedNodeIndex) .WithAdditionalAnnotations(Formatter.Annotation); } private ExpressionSyntax CreateLinqInvocationOrSimpleExpression( ForEachStatementSyntax forEachStatement, ExpressionSyntax receiverForInvocation, IEnumerable<SyntaxTrivia> leadingCommentsTrivia, IEnumerable<SyntaxTrivia> trailingCommentsTrivia, ExpressionSyntax selectExpression, ref int currentExtendedNodeIndex) { leadingCommentsTrivia = forEachStatement.ForEachKeyword.GetAllTrivia().Concat(leadingCommentsTrivia); // Recursively create linq invocations, possibly updating the receiver (Where invocations), to get the inner expression for // the lambda body for the linq invocation to be created for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // if (n1 > n2) // yield return n1 + n2; // // OUTPUT: // c1.SelectMany(n1 => c2.Where(n2 => n1 > n2).Select(n2 => n1 + n2)) // var hasForEachChild = false; var lambdaBody = CreateLinqInvocationForExtendedNode(selectExpression, ref currentExtendedNodeIndex, ref receiverForInvocation, ref hasForEachChild); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( forEachStatement.Identifier.WithPrependedLeadingTrivia( SyntaxNodeOrTokenExtensions.GetTrivia(forEachStatement.Type.GetFirstToken()) .FilterComments(addElasticMarker: false))), lambdaBody) .WithCommentsFrom(leadingCommentsTrivia, trailingCommentsTrivia, forEachStatement.OpenParenToken, forEachStatement.InKeyword, forEachStatement.CloseParenToken); // Create Select or SelectMany linq invocation for this foreach statement. For example: // // INPUT: // foreach (var n1 in c1) // ... // // OUTPUT: // c1.Select(n1 => ... // OR // c1.SelectMany(n1 => ... // var invokedMethodName = !hasForEachChild ? nameof(Enumerable.Select) : nameof(Enumerable.SelectMany); // Avoid `.Select(x => x)` if (invokedMethodName == nameof(Enumerable.Select) && lambdaBody is IdentifierNameSyntax identifier && identifier.Identifier.ValueText == forEachStatement.Identifier.ValueText) { // Because we're dropping the lambda, any comments associated with it need to be preserved. var droppedTrivia = new List<SyntaxTrivia>(); foreach (var token in lambda.DescendantTokens()) { droppedTrivia.AddRange(token.GetAllTrivia().Where(t => !t.IsWhitespace())); } return receiverForInvocation.WithAppendedTrailingTrivia(droppedTrivia); } return SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiverForInvocation.Parenthesize(), SyntaxFactory.IdentifierName(invokedMethodName)), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); } /// <summary> /// Creates a linq invocation expression for the <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> node at the given index <paramref name="extendedNodeIndex"/> /// or returns the <paramref name="selectExpression"/> if all extended nodes have been processed. /// </summary> /// <param name="selectExpression">Innermost select expression</param> /// <param name="extendedNodeIndex">Index into <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> to be processed and updated.</param> /// <param name="receiver">Receiver for the generated linq invocation. Updated when processing an if statement.</param> /// <param name="hasForEachChild">Flag indicating if any of the processed <see cref="ForEachInfo{ForEachStatementSyntax, StatementSyntax}.ConvertingExtendedNodes"/> is a <see cref="ForEachStatementSyntax"/>.</param> private ExpressionSyntax CreateLinqInvocationForExtendedNode( ExpressionSyntax selectExpression, ref int extendedNodeIndex, ref ExpressionSyntax receiver, ref bool hasForEachChild) { // Check if we have converted all the descendant foreach/if statements. // If so, we return the select expression. if (extendedNodeIndex == ForEachInfo.ConvertingExtendedNodes.Length) { return selectExpression; } // Otherwise, convert the next foreach/if statement into a linq invocation. var node = ForEachInfo.ConvertingExtendedNodes[extendedNodeIndex]; switch (node.Node.Kind()) { // Nested ForEach statement is converted into a nested Select or SelectMany linq invocation. For example: // // INPUT: // foreach (var n1 in c1) // foreach (var n2 in c2) // ... // // OUTPUT: // c1.SelectMany(n1 => c2.Select(n2 => ... // case SyntaxKind.ForEachStatement: hasForEachChild = true; var foreachStatement = (ForEachStatementSyntax)node.Node; ++extendedNodeIndex; return CreateLinqInvocationOrSimpleExpression( foreachStatement, receiverForInvocation: foreachStatement.Expression, selectExpression: selectExpression, leadingCommentsTrivia: node.ExtraLeadingComments, trailingCommentsTrivia: node.ExtraTrailingComments, currentExtendedNodeIndex: ref extendedNodeIndex); // Nested If statement is converted into a Where method invocation on the current receiver. For example: // // INPUT: // foreach (var n1 in c1) // if (n1 > 0) // ... // // OUTPUT: // c1.Where(n1 => n1 > 0).Select(n1 => ... // case SyntaxKind.IfStatement: var ifStatement = (IfStatementSyntax)node.Node; var parentForEachStatement = ifStatement.GetAncestor<ForEachStatementSyntax>(); var lambdaParameter = SyntaxFactory.Parameter(SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)); var lambda = SyntaxFactory.SimpleLambdaExpression( SyntaxFactory.Parameter( SyntaxFactory.Identifier(parentForEachStatement.Identifier.ValueText)), ifStatement.Condition.WithCommentsFrom(ifStatement.OpenParenToken, ifStatement.CloseParenToken)) .WithCommentsFrom(ifStatement.IfKeyword.GetAllTrivia().Concat(node.ExtraLeadingComments), node.ExtraTrailingComments); receiver = SyntaxFactory.InvocationExpression( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, receiver.Parenthesize(), SyntaxFactory.IdentifierName(nameof(Enumerable.Where))), SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList( SyntaxFactory.Argument(lambda)))); ++extendedNodeIndex; return CreateLinqInvocationForExtendedNode(selectExpression, ref extendedNodeIndex, ref receiver, ref hasForEachChild); } throw ExceptionUtilities.Unreachable; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/VisualBasic/Portable/CodeGeneration/NamedTypeGenerator.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module NamedTypeGenerator Public Function AddNamedTypeTo(service As ICodeGenerationService, destination As TypeBlockSyntax, namedType As INamedTypeSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), cancellationToken As CancellationToken) As TypeBlockSyntax Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options, cancellationToken) Dim members = Insert(destination.Members, declaration, options, availableIndices) Return FixTerminators(destination.WithMembers(members)) End Function Public Function AddNamedTypeTo(service As ICodeGenerationService, destination As NamespaceBlockSyntax, namedType As INamedTypeSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), cancellationToken As CancellationToken) As NamespaceBlockSyntax Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options, cancellationToken) Dim members = Insert(destination.Members, declaration, options, availableIndices) Return destination.WithMembers(members) End Function Public Function AddNamedTypeTo(service As ICodeGenerationService, destination As CompilationUnitSyntax, namedType As INamedTypeSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), cancellationToken As CancellationToken) As CompilationUnitSyntax Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options, cancellationToken) Dim members = Insert(destination.Members, declaration, options, availableIndices) Return destination.WithMembers(members) End Function Public Function GenerateNamedTypeDeclaration(service As ICodeGenerationService, namedType As INamedTypeSymbol, options As CodeGenerationOptions, cancellationToken As CancellationToken) As StatementSyntax options = If(options, CodeGenerationOptions.Default) Dim declaration = GetDeclarationSyntaxWithoutMembers(namedType, options) declaration = If(options.GenerateMembers AndAlso namedType.TypeKind <> TypeKind.Delegate, service.AddMembers(declaration, GetMembers(namedType), options, cancellationToken), declaration) Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options, cancellationToken)) End Function Public Function UpdateNamedTypeDeclaration(service As ICodeGenerationService, declaration As StatementSyntax, newMembers As IList(Of ISymbol), options As CodeGenerationOptions, cancellationToken As CancellationToken) As StatementSyntax declaration = RemoveAllMembers(declaration) declaration = service.AddMembers(declaration, newMembers, options, cancellationToken) Return AddFormatterAndCodeGeneratorAnnotationsTo(declaration) End Function Private Function GetDeclarationSyntaxWithoutMembers(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax Dim reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol(Of StatementSyntax)(namedType, options) If reusableDeclarationSyntax Is Nothing Then Return GenerateNamedTypeDeclarationWorker(namedType, options) End If Return RemoveAllMembers(reusableDeclarationSyntax) End Function Private Function RemoveAllMembers(declaration As StatementSyntax) As StatementSyntax Select Case declaration.Kind Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).WithMembers(Nothing) Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock Return DirectCast(declaration, TypeBlockSyntax).WithMembers(Nothing) Case Else Return declaration End Select End Function Private Function GenerateNamedTypeDeclarationWorker(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax ' TODO(cyrusn): Support enums/delegates. If namedType.TypeKind = TypeKind.Enum Then Return GenerateEnumDeclaration(namedType, options) ElseIf namedType.TypeKind = TypeKind.Delegate Then Return GenerateDelegateDeclaration(namedType, options) End If Dim isInterface = namedType.TypeKind = TypeKind.Interface Dim isStruct = namedType.TypeKind = TypeKind.Struct Dim isModule = namedType.TypeKind = TypeKind.Module Dim blockKind = If(isInterface, SyntaxKind.InterfaceBlock, If(isStruct, SyntaxKind.StructureBlock, If(isModule, SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock))) Dim statementKind = If(isInterface, SyntaxKind.InterfaceStatement, If(isStruct, SyntaxKind.StructureStatement, If(isModule, SyntaxKind.ModuleStatement, SyntaxKind.ClassStatement))) Dim keywordKind = If(isInterface, SyntaxKind.InterfaceKeyword, If(isStruct, SyntaxKind.StructureKeyword, If(isModule, SyntaxKind.ModuleKeyword, SyntaxKind.ClassKeyword))) Dim endStatement = If(isInterface, SyntaxFactory.EndInterfaceStatement(), If(isStruct, SyntaxFactory.EndStructureStatement(), If(isModule, SyntaxFactory.EndModuleStatement, SyntaxFactory.EndClassStatement))) Dim typeDeclaration = SyntaxFactory.TypeBlock( blockKind, SyntaxFactory.TypeStatement( statementKind, attributes:=GenerateAttributes(namedType, options), modifiers:=GenerateModifiers(namedType), keyword:=SyntaxFactory.Token(keywordKind), identifier:=namedType.Name.ToIdentifierToken(), typeParameterList:=GenerateTypeParameterList(namedType)), [inherits]:=GenerateInheritsStatements(namedType), implements:=GenerateImplementsStatements(namedType), end:=endStatement) Return typeDeclaration End Function Private Function GenerateDelegateDeclaration(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax Dim invokeMethod = namedType.DelegateInvokeMethod Return SyntaxFactory.DelegateStatement( kind:=If(invokeMethod.ReturnsVoid, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement), attributeLists:=GenerateAttributes(namedType, options), modifiers:=GenerateModifiers(namedType), subOrFunctionKeyword:=If(invokeMethod.ReturnsVoid, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=namedType.Name.ToIdentifierToken(), typeParameterList:=GenerateTypeParameterList(namedType), parameterList:=ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, options), asClause:=If(invokeMethod.ReturnsVoid, Nothing, SyntaxFactory.SimpleAsClause(invokeMethod.ReturnType.GenerateTypeSyntax()))) End Function Private Function GenerateEnumDeclaration(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax Dim underlyingType = If(namedType.EnumUnderlyingType IsNot Nothing AndAlso namedType.EnumUnderlyingType.SpecialType <> SpecialType.System_Int32, SyntaxFactory.SimpleAsClause(namedType.EnumUnderlyingType.GenerateTypeSyntax()), Nothing) Return SyntaxFactory.EnumBlock( SyntaxFactory.EnumStatement( GenerateAttributes(namedType, options), GenerateModifiers(namedType), namedType.Name.ToIdentifierToken, underlyingType)) End Function Private Function GenerateAttributes(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As SyntaxList(Of AttributeListSyntax) Return AttributeGenerator.GenerateAttributeBlocks(namedType.GetAttributes(), options) End Function Private Function GenerateModifiers(namedType As INamedTypeSymbol) As SyntaxTokenList Dim tokens = New List(Of SyntaxToken) Select Case namedType.DeclaredAccessibility Case Accessibility.Public tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Protected tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.Private tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Internal tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.ProtectedAndInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.Internal tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Else End Select If namedType.TypeKind = TypeKind.Class Then If namedType.IsSealed Then tokens.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword)) End If If namedType.IsAbstract Then tokens.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword)) End If End If Return SyntaxFactory.TokenList(tokens) End Function Private Function GenerateTypeParameterList(namedType As INamedTypeSymbol) As TypeParameterListSyntax Return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters) End Function Private Function GenerateInheritsStatements(namedType As INamedTypeSymbol) As SyntaxList(Of InheritsStatementSyntax) If namedType.TypeKind = TypeKind.Struct OrElse namedType.BaseType Is Nothing OrElse namedType.BaseType.SpecialType = SpecialType.System_Object Then Return Nothing End If Return SyntaxFactory.SingletonList( SyntaxFactory.InheritsStatement(types:=SyntaxFactory.SingletonSeparatedList(namedType.BaseType.GenerateTypeSyntax()))) End Function Private Function GenerateImplementsStatements(namedType As INamedTypeSymbol) As SyntaxList(Of ImplementsStatementSyntax) If namedType.Interfaces.Length = 0 Then Return Nothing End If Dim types = namedType.Interfaces.Select(Function(t) t.GenerateTypeSyntax()) Dim typeNodes = SyntaxFactory.SeparatedList(types) Return SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(types:=typeNodes)) 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.Threading Imports Microsoft.CodeAnalysis.CodeGeneration Imports Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.CodeGeneration Friend Module NamedTypeGenerator Public Function AddNamedTypeTo(service As ICodeGenerationService, destination As TypeBlockSyntax, namedType As INamedTypeSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), cancellationToken As CancellationToken) As TypeBlockSyntax Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options, cancellationToken) Dim members = Insert(destination.Members, declaration, options, availableIndices) Return FixTerminators(destination.WithMembers(members)) End Function Public Function AddNamedTypeTo(service As ICodeGenerationService, destination As NamespaceBlockSyntax, namedType As INamedTypeSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), cancellationToken As CancellationToken) As NamespaceBlockSyntax Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options, cancellationToken) Dim members = Insert(destination.Members, declaration, options, availableIndices) Return destination.WithMembers(members) End Function Public Function AddNamedTypeTo(service As ICodeGenerationService, destination As CompilationUnitSyntax, namedType As INamedTypeSymbol, options As CodeGenerationOptions, availableIndices As IList(Of Boolean), cancellationToken As CancellationToken) As CompilationUnitSyntax Dim declaration = GenerateNamedTypeDeclaration(service, namedType, options, cancellationToken) Dim members = Insert(destination.Members, declaration, options, availableIndices) Return destination.WithMembers(members) End Function Public Function GenerateNamedTypeDeclaration(service As ICodeGenerationService, namedType As INamedTypeSymbol, options As CodeGenerationOptions, cancellationToken As CancellationToken) As StatementSyntax options = If(options, CodeGenerationOptions.Default) Dim declaration = GetDeclarationSyntaxWithoutMembers(namedType, options) declaration = If(options.GenerateMembers AndAlso namedType.TypeKind <> TypeKind.Delegate, service.AddMembers(declaration, GetMembers(namedType), options, cancellationToken), declaration) Return AddFormatterAndCodeGeneratorAnnotationsTo(ConditionallyAddDocumentationCommentTo(declaration, namedType, options, cancellationToken)) End Function Public Function UpdateNamedTypeDeclaration(service As ICodeGenerationService, declaration As StatementSyntax, newMembers As IList(Of ISymbol), options As CodeGenerationOptions, cancellationToken As CancellationToken) As StatementSyntax declaration = RemoveAllMembers(declaration) declaration = service.AddMembers(declaration, newMembers, options, cancellationToken) Return AddFormatterAndCodeGeneratorAnnotationsTo(declaration) End Function Private Function GetDeclarationSyntaxWithoutMembers(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax Dim reusableDeclarationSyntax = GetReuseableSyntaxNodeForSymbol(Of StatementSyntax)(namedType, options) If reusableDeclarationSyntax Is Nothing Then Return GenerateNamedTypeDeclarationWorker(namedType, options) End If Return RemoveAllMembers(reusableDeclarationSyntax) End Function Private Function RemoveAllMembers(declaration As StatementSyntax) As StatementSyntax Select Case declaration.Kind Case SyntaxKind.EnumBlock Return DirectCast(declaration, EnumBlockSyntax).WithMembers(Nothing) Case SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ClassBlock Return DirectCast(declaration, TypeBlockSyntax).WithMembers(Nothing) Case Else Return declaration End Select End Function Private Function GenerateNamedTypeDeclarationWorker(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax ' TODO(cyrusn): Support enums/delegates. If namedType.TypeKind = TypeKind.Enum Then Return GenerateEnumDeclaration(namedType, options) ElseIf namedType.TypeKind = TypeKind.Delegate Then Return GenerateDelegateDeclaration(namedType, options) End If Dim isInterface = namedType.TypeKind = TypeKind.Interface Dim isStruct = namedType.TypeKind = TypeKind.Struct Dim isModule = namedType.TypeKind = TypeKind.Module Dim blockKind = If(isInterface, SyntaxKind.InterfaceBlock, If(isStruct, SyntaxKind.StructureBlock, If(isModule, SyntaxKind.ModuleBlock, SyntaxKind.ClassBlock))) Dim statementKind = If(isInterface, SyntaxKind.InterfaceStatement, If(isStruct, SyntaxKind.StructureStatement, If(isModule, SyntaxKind.ModuleStatement, SyntaxKind.ClassStatement))) Dim keywordKind = If(isInterface, SyntaxKind.InterfaceKeyword, If(isStruct, SyntaxKind.StructureKeyword, If(isModule, SyntaxKind.ModuleKeyword, SyntaxKind.ClassKeyword))) Dim endStatement = If(isInterface, SyntaxFactory.EndInterfaceStatement(), If(isStruct, SyntaxFactory.EndStructureStatement(), If(isModule, SyntaxFactory.EndModuleStatement, SyntaxFactory.EndClassStatement))) Dim typeDeclaration = SyntaxFactory.TypeBlock( blockKind, SyntaxFactory.TypeStatement( statementKind, attributes:=GenerateAttributes(namedType, options), modifiers:=GenerateModifiers(namedType), keyword:=SyntaxFactory.Token(keywordKind), identifier:=namedType.Name.ToIdentifierToken(), typeParameterList:=GenerateTypeParameterList(namedType)), [inherits]:=GenerateInheritsStatements(namedType), implements:=GenerateImplementsStatements(namedType), end:=endStatement) Return typeDeclaration End Function Private Function GenerateDelegateDeclaration(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax Dim invokeMethod = namedType.DelegateInvokeMethod Return SyntaxFactory.DelegateStatement( kind:=If(invokeMethod.ReturnsVoid, SyntaxKind.DelegateSubStatement, SyntaxKind.DelegateFunctionStatement), attributeLists:=GenerateAttributes(namedType, options), modifiers:=GenerateModifiers(namedType), subOrFunctionKeyword:=If(invokeMethod.ReturnsVoid, SyntaxFactory.Token(SyntaxKind.SubKeyword), SyntaxFactory.Token(SyntaxKind.FunctionKeyword)), identifier:=namedType.Name.ToIdentifierToken(), typeParameterList:=GenerateTypeParameterList(namedType), parameterList:=ParameterGenerator.GenerateParameterList(invokeMethod.Parameters, options), asClause:=If(invokeMethod.ReturnsVoid, Nothing, SyntaxFactory.SimpleAsClause(invokeMethod.ReturnType.GenerateTypeSyntax()))) End Function Private Function GenerateEnumDeclaration(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As StatementSyntax Dim underlyingType = If(namedType.EnumUnderlyingType IsNot Nothing AndAlso namedType.EnumUnderlyingType.SpecialType <> SpecialType.System_Int32, SyntaxFactory.SimpleAsClause(namedType.EnumUnderlyingType.GenerateTypeSyntax()), Nothing) Return SyntaxFactory.EnumBlock( SyntaxFactory.EnumStatement( GenerateAttributes(namedType, options), GenerateModifiers(namedType), namedType.Name.ToIdentifierToken, underlyingType)) End Function Private Function GenerateAttributes(namedType As INamedTypeSymbol, options As CodeGenerationOptions) As SyntaxList(Of AttributeListSyntax) Return AttributeGenerator.GenerateAttributeBlocks(namedType.GetAttributes(), options) End Function Private Function GenerateModifiers(namedType As INamedTypeSymbol) As SyntaxTokenList Dim tokens = New List(Of SyntaxToken) Select Case namedType.DeclaredAccessibility Case Accessibility.Public tokens.Add(SyntaxFactory.Token(SyntaxKind.PublicKeyword)) Case Accessibility.Protected tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.Private tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) Case Accessibility.Internal tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.ProtectedAndInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) Case Accessibility.ProtectedOrInternal tokens.Add(SyntaxFactory.Token(SyntaxKind.ProtectedKeyword)) tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Accessibility.Internal tokens.Add(SyntaxFactory.Token(SyntaxKind.FriendKeyword)) Case Else End Select If namedType.TypeKind = TypeKind.Class Then If namedType.IsSealed Then tokens.Add(SyntaxFactory.Token(SyntaxKind.NotInheritableKeyword)) End If If namedType.IsAbstract Then tokens.Add(SyntaxFactory.Token(SyntaxKind.MustInheritKeyword)) End If End If Return SyntaxFactory.TokenList(tokens) End Function Private Function GenerateTypeParameterList(namedType As INamedTypeSymbol) As TypeParameterListSyntax Return TypeParameterGenerator.GenerateTypeParameterList(namedType.TypeParameters) End Function Private Function GenerateInheritsStatements(namedType As INamedTypeSymbol) As SyntaxList(Of InheritsStatementSyntax) If namedType.TypeKind = TypeKind.Struct OrElse namedType.BaseType Is Nothing OrElse namedType.BaseType.SpecialType = SpecialType.System_Object Then Return Nothing End If Return SyntaxFactory.SingletonList( SyntaxFactory.InheritsStatement(types:=SyntaxFactory.SingletonSeparatedList(namedType.BaseType.GenerateTypeSyntax()))) End Function Private Function GenerateImplementsStatements(namedType As INamedTypeSymbol) As SyntaxList(Of ImplementsStatementSyntax) If namedType.Interfaces.Length = 0 Then Return Nothing End If Dim types = namedType.Interfaces.Select(Function(t) t.GenerateTypeSyntax()) Dim typeNodes = SyntaxFactory.SeparatedList(types) Return SyntaxFactory.SingletonList(SyntaxFactory.ImplementsStatement(types:=typeNodes)) End Function End Module End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/CSharp/Portable/Organizing/Organizers/MemberDeclarationsOrganizer.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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { internal static partial class MemberDeclarationsOrganizer { public static SyntaxList<MemberDeclarationSyntax> Organize( SyntaxList<MemberDeclarationSyntax> members, CancellationToken cancellationToken) { // Break the list of members up into groups based on the PP // directives between them. var groups = members.SplitNodesOnPreprocessorBoundaries(cancellationToken); // Go into each group and organize them. We'll then have a list of // lists. Flatten that list and return that. var sortedGroups = groups.Select(OrganizeMemberGroup).Flatten().ToList(); if (sortedGroups.SequenceEqual(members)) { return members; } return sortedGroups.ToSyntaxList(); } private static void TransferTrivia<TSyntaxNode>( IList<TSyntaxNode> originalList, IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode { Debug.Assert(originalList.Count == finalList.Count); if (originalList.Count >= 2) { // Ok, we wanted to reorder the list. But we're definitely not done right now. While // most of the list will look fine, we will have issues with the first node. First, // we don't want to move any pp directives or banners that are on the first node. // Second, it can often be the case that the node doesn't even have any trivia. We // want to follow the user's style. So we find the node that was in the index that // the first node moved to, and we attempt to keep an appropriate amount of // whitespace based on that. // If the first node didn't move, then we don't need to do any of this special fixup // logic. if (originalList[0] != finalList[0]) { // First. Strip any pp directives or banners on the first node. They have to // move to the first node in the final list. CopyBanner(originalList, finalList); // Now, we need to fix up the first node wherever it is in the final list. We // need to strip it of its banner, and we need to add additional whitespace to // match the user's style FixupOriginalFirstNode(originalList, finalList); } } } private static void FixupOriginalFirstNode<TSyntaxNode>(IList<TSyntaxNode> originalList, IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode { // Now, find the original node in the final list. var originalFirstNode = originalList[0]; var indexInFinalList = finalList.IndexOf(originalFirstNode); // Find the initial node we had at that same index. var originalNodeAtThatIndex = originalList[indexInFinalList]; // If that node had blank lines above it, then place that number of blank // lines before the first node in the final list. var blankLines = originalNodeAtThatIndex.GetLeadingBlankLines(); originalFirstNode = originalFirstNode.GetNodeWithoutLeadingBannerAndPreprocessorDirectives() .WithPrependedLeadingTrivia(blankLines); finalList[indexInFinalList] = originalFirstNode; } private static void CopyBanner<TSyntaxNode>( IList<TSyntaxNode> originalList, IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode { // First. Strip any pp directives or banners on the first node. They // have to stay at the top of the list. var banner = originalList[0].GetLeadingBannerAndPreprocessorDirectives(); // Now, we want to remove any blank lines from the new first node and then // reattach the banner. var finalFirstNode = finalList[0]; finalFirstNode = finalFirstNode.GetNodeWithoutLeadingBlankLines(); finalFirstNode = finalFirstNode.WithLeadingTrivia(banner.Concat(finalFirstNode.GetLeadingTrivia())); // Place the updated first node back in the result list finalList[0] = finalFirstNode; } private static IList<MemberDeclarationSyntax> OrganizeMemberGroup(IList<MemberDeclarationSyntax> members) { if (members.Count > 1) { var initialList = new List<MemberDeclarationSyntax>(members); var finalList = initialList.OrderBy(new Comparer()).ToList(); if (!finalList.SequenceEqual(initialList)) { // Ok, we wanted to reorder the list. But we're definitely not done right now. // While most of the list will look fine, we will have issues with the first // node. First, we don't want to move any pp directives or banners that are on // the first node. Second, it can often be the case that the node doesn't even // have any trivia. We want to follow the user's style. So we find the node that // was in the index that the first node moved to, and we attempt to keep an // appropriate amount of whitespace based on that. TransferTrivia(initialList, finalList); return finalList; } } return members; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers { internal static partial class MemberDeclarationsOrganizer { public static SyntaxList<MemberDeclarationSyntax> Organize( SyntaxList<MemberDeclarationSyntax> members, CancellationToken cancellationToken) { // Break the list of members up into groups based on the PP // directives between them. var groups = members.SplitNodesOnPreprocessorBoundaries(cancellationToken); // Go into each group and organize them. We'll then have a list of // lists. Flatten that list and return that. var sortedGroups = groups.Select(OrganizeMemberGroup).Flatten().ToList(); if (sortedGroups.SequenceEqual(members)) { return members; } return sortedGroups.ToSyntaxList(); } private static void TransferTrivia<TSyntaxNode>( IList<TSyntaxNode> originalList, IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode { Debug.Assert(originalList.Count == finalList.Count); if (originalList.Count >= 2) { // Ok, we wanted to reorder the list. But we're definitely not done right now. While // most of the list will look fine, we will have issues with the first node. First, // we don't want to move any pp directives or banners that are on the first node. // Second, it can often be the case that the node doesn't even have any trivia. We // want to follow the user's style. So we find the node that was in the index that // the first node moved to, and we attempt to keep an appropriate amount of // whitespace based on that. // If the first node didn't move, then we don't need to do any of this special fixup // logic. if (originalList[0] != finalList[0]) { // First. Strip any pp directives or banners on the first node. They have to // move to the first node in the final list. CopyBanner(originalList, finalList); // Now, we need to fix up the first node wherever it is in the final list. We // need to strip it of its banner, and we need to add additional whitespace to // match the user's style FixupOriginalFirstNode(originalList, finalList); } } } private static void FixupOriginalFirstNode<TSyntaxNode>(IList<TSyntaxNode> originalList, IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode { // Now, find the original node in the final list. var originalFirstNode = originalList[0]; var indexInFinalList = finalList.IndexOf(originalFirstNode); // Find the initial node we had at that same index. var originalNodeAtThatIndex = originalList[indexInFinalList]; // If that node had blank lines above it, then place that number of blank // lines before the first node in the final list. var blankLines = originalNodeAtThatIndex.GetLeadingBlankLines(); originalFirstNode = originalFirstNode.GetNodeWithoutLeadingBannerAndPreprocessorDirectives() .WithPrependedLeadingTrivia(blankLines); finalList[indexInFinalList] = originalFirstNode; } private static void CopyBanner<TSyntaxNode>( IList<TSyntaxNode> originalList, IList<TSyntaxNode> finalList) where TSyntaxNode : SyntaxNode { // First. Strip any pp directives or banners on the first node. They // have to stay at the top of the list. var banner = originalList[0].GetLeadingBannerAndPreprocessorDirectives(); // Now, we want to remove any blank lines from the new first node and then // reattach the banner. var finalFirstNode = finalList[0]; finalFirstNode = finalFirstNode.GetNodeWithoutLeadingBlankLines(); finalFirstNode = finalFirstNode.WithLeadingTrivia(banner.Concat(finalFirstNode.GetLeadingTrivia())); // Place the updated first node back in the result list finalList[0] = finalFirstNode; } private static IList<MemberDeclarationSyntax> OrganizeMemberGroup(IList<MemberDeclarationSyntax> members) { if (members.Count > 1) { var initialList = new List<MemberDeclarationSyntax>(members); var finalList = initialList.OrderBy(new Comparer()).ToList(); if (!finalList.SequenceEqual(initialList)) { // Ok, we wanted to reorder the list. But we're definitely not done right now. // While most of the list will look fine, we will have issues with the first // node. First, we don't want to move any pp directives or banners that are on // the first node. Second, it can often be the case that the node doesn't even // have any trivia. We want to follow the user's style. So we find the node that // was in the index that the first node moved to, and we attempt to keep an // appropriate amount of whitespace based on that. TransferTrivia(initialList, finalList); return finalList; } } return members; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/Core/Portable/Diagnostics/DiagnosticAnalyzerService_BuildSynchronization.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 Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class DiagnosticAnalyzerService { /// <summary> /// Synchronize build errors with live error. /// </summary> public ValueTask SynchronizeWithBuildAsync( Workspace workspace, ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>> diagnostics, TaskQueue postBuildAndErrorListRefreshTaskQueue, bool onBuildCompleted, CancellationToken cancellationToken) { return _map.TryGetValue(workspace, out var analyzer) ? analyzer.SynchronizeWithBuildAsync(diagnostics, postBuildAndErrorListRefreshTaskQueue, onBuildCompleted, cancellationToken) : default; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics { internal partial class DiagnosticAnalyzerService { /// <summary> /// Synchronize build errors with live error. /// </summary> public ValueTask SynchronizeWithBuildAsync( Workspace workspace, ImmutableDictionary<ProjectId, ImmutableArray<DiagnosticData>> diagnostics, TaskQueue postBuildAndErrorListRefreshTaskQueue, bool onBuildCompleted, CancellationToken cancellationToken) { return _map.TryGetValue(workspace, out var analyzer) ? analyzer.SynchronizeWithBuildAsync(diagnostics, postBuildAndErrorListRefreshTaskQueue, onBuildCompleted, cancellationToken) : default; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Portable/Symbols/Source/LocalFunctionSymbol.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; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class LocalFunctionSymbol : SourceMethodSymbolWithAttributes { private readonly Binder _binder; private readonly Symbol _containingSymbol; private readonly DeclarationModifiers _declarationModifiers; private readonly ImmutableArray<SourceMethodTypeParameterSymbol> _typeParameters; private readonly RefKind _refKind; private ImmutableArray<ParameterSymbol> _lazyParameters; private bool _lazyIsVarArg; // Initialized in two steps. Hold a copy if accessing during initialization. private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; private TypeWithAnnotations.Boxed? _lazyReturnType; private TypeWithAnnotations.Boxed? _lazyIteratorElementType; // Lock for initializing lazy fields and registering their diagnostics // Acquire this lock when initializing lazy objects to guarantee their declaration // diagnostics get added to the store exactly once private readonly BindingDiagnosticBag _declarationDiagnostics; public LocalFunctionSymbol( Binder binder, Symbol containingSymbol, LocalFunctionStatementSyntax syntax) : base(syntax.GetReference()) { _containingSymbol = containingSymbol; _declarationDiagnostics = new BindingDiagnosticBag(); _declarationModifiers = DeclarationModifiers.Private | syntax.Modifiers.ToDeclarationModifiers(diagnostics: _declarationDiagnostics.DiagnosticBag); if (SyntaxFacts.HasYieldOperations(syntax.Body)) { _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; } this.CheckUnsafeModifier(_declarationModifiers, _declarationDiagnostics); ScopeBinder = binder; binder = binder.WithUnsafeRegionIfNecessary(syntax.Modifiers); if (syntax.TypeParameterList != null) { binder = new WithMethodTypeParametersBinder(this, binder); _typeParameters = MakeTypeParameters(_declarationDiagnostics); } else { _typeParameters = ImmutableArray<SourceMethodTypeParameterSymbol>.Empty; ReportErrorIfHasConstraints(syntax.ConstraintClauses, _declarationDiagnostics.DiagnosticBag); } if (IsExtensionMethod) { _declarationDiagnostics.Add(ErrorCode.ERR_BadExtensionAgg, Locations[0]); } foreach (var param in syntax.ParameterList.Parameters) { ReportAttributesDisallowed(param.AttributeLists, _declarationDiagnostics); } if (syntax.ReturnType.Kind() == SyntaxKind.RefType) { var returnType = (RefTypeSyntax)syntax.ReturnType; if (returnType.ReadOnlyKeyword.Kind() == SyntaxKind.ReadOnlyKeyword) { _refKind = RefKind.RefReadOnly; } else { _refKind = RefKind.Ref; } } else { _refKind = RefKind.None; } _binder = binder; } /// <summary> /// Binder that owns the scope for the local function symbol, namely the scope where the /// local function is declared. /// </summary> internal Binder ScopeBinder { get; } internal override Binder ParameterBinder => _binder; internal LocalFunctionStatementSyntax Syntax => (LocalFunctionStatementSyntax)syntaxReferenceOpt.GetSyntax(); internal void GetDeclarationDiagnostics(BindingDiagnosticBag addTo) { // Force complete type parameters foreach (var typeParam in _typeParameters) { typeParam.ForceComplete(null, default(CancellationToken)); } // force lazy init ComputeParameters(); foreach (var p in _lazyParameters) { // Force complete parameters to retrieve all diagnostics p.ForceComplete(null, default(CancellationToken)); } ComputeReturnType(); GetAttributes(); GetReturnTypeAttributes(); AsyncMethodChecks(_declarationDiagnostics); addTo.AddRange(_declarationDiagnostics, allowMismatchInDependencyAccumulation: true); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: false, withDependencies: addTo.AccumulatesDependencies); if (IsEntryPointCandidate && !IsGenericMethod && ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol && DeclaringCompilation.HasEntryPointSignature(this, diagnostics).IsCandidate) { addTo.Add(ErrorCode.WRN_MainIgnored, Syntax.Identifier.GetLocation(), this); } addTo.AddRangeAndFree(diagnostics); } internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => _declarationDiagnostics.AddRange(diagnostics); public override bool RequiresInstanceReceiver => false; public override bool IsVararg { get { ComputeParameters(); return _lazyIsVarArg; } } public override ImmutableArray<ParameterSymbol> Parameters { get { ComputeParameters(); return _lazyParameters; } } private void ComputeParameters() { if (_lazyParameters != null) { return; } SyntaxToken arglistToken; var diagnostics = BindingDiagnosticBag.GetInstance(_declarationDiagnostics); var parameters = ParameterHelpers.MakeParameters( _binder, this, this.Syntax.ParameterList, arglistToken: out arglistToken, allowRefOrOut: true, allowThis: true, addRefReadOnlyModifier: false, diagnostics: diagnostics); var compilation = DeclaringCompilation; ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, parameters, diagnostics, modifyCompilation: false); ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, parameters, diagnostics, modifyCompilation: false); ParameterHelpers.EnsureNullableAttributeExists(compilation, this, parameters, diagnostics, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for local functions, as this is handled in binding already var isVararg = arglistToken.Kind() == SyntaxKind.ArgListKeyword; if (isVararg) { diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation()); } lock (_declarationDiagnostics) { if (_lazyParameters != null) { diagnostics.Free(); return; } _declarationDiagnostics.AddRangeAndFree(diagnostics); _lazyIsVarArg = isVararg; _lazyParameters = parameters; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { ComputeReturnType(); return _lazyReturnType!.Value; } } public override RefKind RefKind => _refKind; internal void ComputeReturnType() { if (_lazyReturnType is object) { return; } var diagnostics = BindingDiagnosticBag.GetInstance(_declarationDiagnostics); TypeSyntax returnTypeSyntax = Syntax.ReturnType; TypeWithAnnotations returnType = _binder.BindType(returnTypeSyntax.SkipRef(), diagnostics); var compilation = DeclaringCompilation; // Skip some diagnostics when the local function is not associated with a compilation // (specifically, local functions nested in expressions in the EE). if (compilation is object) { var location = returnTypeSyntax.Location; if (_refKind == RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: false); } if (returnType.Type.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: false); } if (compilation.ShouldEmitNullableAttributes(this) && returnType.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for local functions, as this is handled in binding already } } // span-like types are returnable in general if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeSyntax.Location, returnType.Type); } Debug.Assert(_refKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors); lock (_declarationDiagnostics) { if (_lazyReturnType is object) { diagnostics.Free(); return; } _declarationDiagnostics.AddRangeAndFree(diagnostics); Interlocked.CompareExchange(ref _lazyReturnType, new TypeWithAnnotations.Boxed(returnType), null); } } public override bool ReturnsVoid => ReturnType.IsVoidType(); public override int Arity => TypeParameters.Length; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations => GetTypeParametersAsTypeArguments(); public override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters.Cast<SourceMethodTypeParameterSymbol, TypeParameterSymbol>(); public override bool IsExtensionMethod { get { // It is an error to be an extension method, but we need to compute it to report it var firstParam = Syntax.ParameterList.Parameters.FirstOrDefault(); return firstParam != null && !firstParam.IsArgList && firstParam.Modifiers.Any(SyntaxKind.ThisKeyword); } } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { return _lazyIteratorElementType?.Value ?? default; } set { Debug.Assert(_lazyIteratorElementType == TypeWithAnnotations.Boxed.Sentinel || (_lazyIteratorElementType is object && TypeSymbol.Equals(_lazyIteratorElementType.Value.Type, value.Type, TypeCompareKind.ConsiderEverything2))); Interlocked.CompareExchange(ref _lazyIteratorElementType, new TypeWithAnnotations.Boxed(value), TypeWithAnnotations.Boxed.Sentinel); } } internal override bool IsIterator => _lazyIteratorElementType is object; public override MethodKind MethodKind => MethodKind.LocalFunction; public sealed override Symbol ContainingSymbol => _containingSymbol; public override string Name => Syntax.Identifier.ValueText ?? ""; public SyntaxToken NameToken => Syntax.Identifier; internal override Binder SignatureBinder => _binder; public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations => ImmutableArray<MethodSymbol>.Empty; public override ImmutableArray<Location> Locations => ImmutableArray.Create(Syntax.Identifier.GetLocation()); internal override bool GenerateDebugInfo => true; public override ImmutableArray<CustomModifier> RefCustomModifiers => ImmutableArray<CustomModifier>.Empty; internal override CallingConvention CallingConvention => CallingConvention.Default; internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { return OneOrMany.Create(Syntax.AttributeLists); } protected override void NoteAttributesComplete(bool forReturnType) { } public override Symbol? AssociatedSymbol => null; public override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(_declarationModifiers); public override bool IsAsync => (_declarationModifiers & DeclarationModifiers.Async) != 0; public override bool IsStatic => (_declarationModifiers & DeclarationModifiers.Static) != 0; public override bool IsVirtual => (_declarationModifiers & DeclarationModifiers.Virtual) != 0; public override bool IsOverride => (_declarationModifiers & DeclarationModifiers.Override) != 0; public override bool IsAbstract => (_declarationModifiers & DeclarationModifiers.Abstract) != 0; public override bool IsSealed => (_declarationModifiers & DeclarationModifiers.Sealed) != 0; public override bool IsExtern => (_declarationModifiers & DeclarationModifiers.Extern) != 0; public bool IsUnsafe => (_declarationModifiers & DeclarationModifiers.Unsafe) != 0; internal bool IsExpressionBodied => Syntax is { Body: null, ExpressionBody: object _ }; internal override bool IsDeclaredReadOnly => false; internal override bool IsInitOnly => false; internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) => false; internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) => false; internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { throw ExceptionUtilities.Unreachable; } internal override bool TryGetThisParameter(out ParameterSymbol? thisParameter) { // Local function symbols have no "this" parameter thisParameter = null; return true; } private void ReportAttributesDisallowed(SyntaxList<AttributeListSyntax> attributes, BindingDiagnosticBag diagnostics) { var diagnosticInfo = MessageID.IDS_FeatureLocalFunctionAttributes.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)syntaxReferenceOpt.SyntaxTree.Options); if (diagnosticInfo is object) { foreach (var attrList in attributes) { diagnostics.Add(diagnosticInfo, attrList.Location); } } } private ImmutableArray<SourceMethodTypeParameterSymbol> MakeTypeParameters(BindingDiagnosticBag diagnostics) { var result = ArrayBuilder<SourceMethodTypeParameterSymbol>.GetInstance(); var typeParameters = Syntax.TypeParameterList?.Parameters ?? default; for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++) { var parameter = typeParameters[ordinal]; if (parameter.VarianceKeyword.Kind() != SyntaxKind.None) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation()); } ReportAttributesDisallowed(parameter.AttributeLists, diagnostics); var identifier = parameter.Identifier; var location = identifier.GetLocation(); var name = identifier.ValueText ?? ""; foreach (var @param in result) { if (name == @param.Name) { diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); break; } } SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); var tpEnclosing = ContainingSymbol.FindEnclosingTypeParameter(name); if ((object?)tpEnclosing != null) { ErrorCode typeError; if (tpEnclosing.ContainingSymbol.Kind == SymbolKind.Method) { // Type parameter '{0}' has the same name as the type parameter from outer method '{1}' typeError = ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter; } else { Debug.Assert(tpEnclosing.ContainingSymbol.Kind == SymbolKind.NamedType); // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' typeError = ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter; } diagnostics.Add(typeError, location, name, tpEnclosing.ContainingSymbol); } var typeParameter = new SourceMethodTypeParameterSymbol( this, name, ordinal, ImmutableArray.Create(location), ImmutableArray.Create(parameter.GetReference())); result.Add(typeParameter); } return result.ToImmutableAndFree(); } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { if (_lazyTypeParameterConstraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var syntax = Syntax; var diagnostics = BindingDiagnosticBag.GetInstance(_declarationDiagnostics); var constraints = this.MakeTypeParameterConstraintTypes( _binder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics); lock (_declarationDiagnostics) { if (_lazyTypeParameterConstraintTypes.IsDefault) { _declarationDiagnostics.AddRange(diagnostics); _lazyTypeParameterConstraintTypes = constraints; } } diagnostics.Free(); } return _lazyTypeParameterConstraintTypes; } public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { if (_lazyTypeParameterConstraintKinds.IsDefault) { var syntax = Syntax; var constraints = this.MakeTypeParameterConstraintKinds( _binder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); } return _lazyTypeParameterConstraintKinds; } internal override bool IsNullableAnalysisEnabled() => throw ExceptionUtilities.Unreachable; public override int GetHashCode() { // this is what lambdas do (do not use hashes of other fields) return Syntax.GetHashCode(); } public sealed override bool Equals(Symbol symbol, TypeCompareKind compareKind) { if ((object)this == symbol) return true; var localFunction = symbol as LocalFunctionSymbol; return localFunction?.Syntax == Syntax; } } }
// Licensed to the .NET Foundation under one or more 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; using Microsoft.Cci; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { internal sealed class LocalFunctionSymbol : SourceMethodSymbolWithAttributes { private readonly Binder _binder; private readonly Symbol _containingSymbol; private readonly DeclarationModifiers _declarationModifiers; private readonly ImmutableArray<SourceMethodTypeParameterSymbol> _typeParameters; private readonly RefKind _refKind; private ImmutableArray<ParameterSymbol> _lazyParameters; private bool _lazyIsVarArg; // Initialized in two steps. Hold a copy if accessing during initialization. private ImmutableArray<ImmutableArray<TypeWithAnnotations>> _lazyTypeParameterConstraintTypes; private ImmutableArray<TypeParameterConstraintKind> _lazyTypeParameterConstraintKinds; private TypeWithAnnotations.Boxed? _lazyReturnType; private TypeWithAnnotations.Boxed? _lazyIteratorElementType; // Lock for initializing lazy fields and registering their diagnostics // Acquire this lock when initializing lazy objects to guarantee their declaration // diagnostics get added to the store exactly once private readonly BindingDiagnosticBag _declarationDiagnostics; public LocalFunctionSymbol( Binder binder, Symbol containingSymbol, LocalFunctionStatementSyntax syntax) : base(syntax.GetReference()) { _containingSymbol = containingSymbol; _declarationDiagnostics = new BindingDiagnosticBag(); _declarationModifiers = DeclarationModifiers.Private | syntax.Modifiers.ToDeclarationModifiers(diagnostics: _declarationDiagnostics.DiagnosticBag); if (SyntaxFacts.HasYieldOperations(syntax.Body)) { _lazyIteratorElementType = TypeWithAnnotations.Boxed.Sentinel; } this.CheckUnsafeModifier(_declarationModifiers, _declarationDiagnostics); ScopeBinder = binder; binder = binder.WithUnsafeRegionIfNecessary(syntax.Modifiers); if (syntax.TypeParameterList != null) { binder = new WithMethodTypeParametersBinder(this, binder); _typeParameters = MakeTypeParameters(_declarationDiagnostics); } else { _typeParameters = ImmutableArray<SourceMethodTypeParameterSymbol>.Empty; ReportErrorIfHasConstraints(syntax.ConstraintClauses, _declarationDiagnostics.DiagnosticBag); } if (IsExtensionMethod) { _declarationDiagnostics.Add(ErrorCode.ERR_BadExtensionAgg, Locations[0]); } foreach (var param in syntax.ParameterList.Parameters) { ReportAttributesDisallowed(param.AttributeLists, _declarationDiagnostics); } if (syntax.ReturnType.Kind() == SyntaxKind.RefType) { var returnType = (RefTypeSyntax)syntax.ReturnType; if (returnType.ReadOnlyKeyword.Kind() == SyntaxKind.ReadOnlyKeyword) { _refKind = RefKind.RefReadOnly; } else { _refKind = RefKind.Ref; } } else { _refKind = RefKind.None; } _binder = binder; } /// <summary> /// Binder that owns the scope for the local function symbol, namely the scope where the /// local function is declared. /// </summary> internal Binder ScopeBinder { get; } internal override Binder ParameterBinder => _binder; internal LocalFunctionStatementSyntax Syntax => (LocalFunctionStatementSyntax)syntaxReferenceOpt.GetSyntax(); internal void GetDeclarationDiagnostics(BindingDiagnosticBag addTo) { // Force complete type parameters foreach (var typeParam in _typeParameters) { typeParam.ForceComplete(null, default(CancellationToken)); } // force lazy init ComputeParameters(); foreach (var p in _lazyParameters) { // Force complete parameters to retrieve all diagnostics p.ForceComplete(null, default(CancellationToken)); } ComputeReturnType(); GetAttributes(); GetReturnTypeAttributes(); AsyncMethodChecks(_declarationDiagnostics); addTo.AddRange(_declarationDiagnostics, allowMismatchInDependencyAccumulation: true); var diagnostics = BindingDiagnosticBag.GetInstance(withDiagnostics: false, withDependencies: addTo.AccumulatesDependencies); if (IsEntryPointCandidate && !IsGenericMethod && ContainingSymbol is SynthesizedSimpleProgramEntryPointSymbol && DeclaringCompilation.HasEntryPointSignature(this, diagnostics).IsCandidate) { addTo.Add(ErrorCode.WRN_MainIgnored, Syntax.Identifier.GetLocation(), this); } addTo.AddRangeAndFree(diagnostics); } internal override void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) => _declarationDiagnostics.AddRange(diagnostics); public override bool RequiresInstanceReceiver => false; public override bool IsVararg { get { ComputeParameters(); return _lazyIsVarArg; } } public override ImmutableArray<ParameterSymbol> Parameters { get { ComputeParameters(); return _lazyParameters; } } private void ComputeParameters() { if (_lazyParameters != null) { return; } SyntaxToken arglistToken; var diagnostics = BindingDiagnosticBag.GetInstance(_declarationDiagnostics); var parameters = ParameterHelpers.MakeParameters( _binder, this, this.Syntax.ParameterList, arglistToken: out arglistToken, allowRefOrOut: true, allowThis: true, addRefReadOnlyModifier: false, diagnostics: diagnostics); var compilation = DeclaringCompilation; ParameterHelpers.EnsureIsReadOnlyAttributeExists(compilation, parameters, diagnostics, modifyCompilation: false); ParameterHelpers.EnsureNativeIntegerAttributeExists(compilation, parameters, diagnostics, modifyCompilation: false); ParameterHelpers.EnsureNullableAttributeExists(compilation, this, parameters, diagnostics, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for local functions, as this is handled in binding already var isVararg = arglistToken.Kind() == SyntaxKind.ArgListKeyword; if (isVararg) { diagnostics.Add(ErrorCode.ERR_IllegalVarArgs, arglistToken.GetLocation()); } lock (_declarationDiagnostics) { if (_lazyParameters != null) { diagnostics.Free(); return; } _declarationDiagnostics.AddRangeAndFree(diagnostics); _lazyIsVarArg = isVararg; _lazyParameters = parameters; } } public override TypeWithAnnotations ReturnTypeWithAnnotations { get { ComputeReturnType(); return _lazyReturnType!.Value; } } public override RefKind RefKind => _refKind; internal void ComputeReturnType() { if (_lazyReturnType is object) { return; } var diagnostics = BindingDiagnosticBag.GetInstance(_declarationDiagnostics); TypeSyntax returnTypeSyntax = Syntax.ReturnType; TypeWithAnnotations returnType = _binder.BindType(returnTypeSyntax.SkipRef(), diagnostics); var compilation = DeclaringCompilation; // Skip some diagnostics when the local function is not associated with a compilation // (specifically, local functions nested in expressions in the EE). if (compilation is object) { var location = returnTypeSyntax.Location; if (_refKind == RefKind.RefReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: false); } if (returnType.Type.ContainsNativeInteger()) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: false); } if (compilation.ShouldEmitNullableAttributes(this) && returnType.NeedsNullableAttribute()) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: false); // Note: we don't need to warn on annotations used in #nullable disable context for local functions, as this is handled in binding already } } // span-like types are returnable in general if (returnType.IsRestrictedType(ignoreSpanLikeTypes: true)) { // The return type of a method, delegate, or function pointer cannot be '{0}' diagnostics.Add(ErrorCode.ERR_MethodReturnCantBeRefAny, returnTypeSyntax.Location, returnType.Type); } Debug.Assert(_refKind == RefKind.None || !returnType.IsVoidType() || returnTypeSyntax.HasErrors); lock (_declarationDiagnostics) { if (_lazyReturnType is object) { diagnostics.Free(); return; } _declarationDiagnostics.AddRangeAndFree(diagnostics); Interlocked.CompareExchange(ref _lazyReturnType, new TypeWithAnnotations.Boxed(returnType), null); } } public override bool ReturnsVoid => ReturnType.IsVoidType(); public override int Arity => TypeParameters.Length; public override ImmutableArray<TypeWithAnnotations> TypeArgumentsWithAnnotations => GetTypeParametersAsTypeArguments(); public override ImmutableArray<TypeParameterSymbol> TypeParameters => _typeParameters.Cast<SourceMethodTypeParameterSymbol, TypeParameterSymbol>(); public override bool IsExtensionMethod { get { // It is an error to be an extension method, but we need to compute it to report it var firstParam = Syntax.ParameterList.Parameters.FirstOrDefault(); return firstParam != null && !firstParam.IsArgList && firstParam.Modifiers.Any(SyntaxKind.ThisKeyword); } } internal override TypeWithAnnotations IteratorElementTypeWithAnnotations { get { return _lazyIteratorElementType?.Value ?? default; } set { Debug.Assert(_lazyIteratorElementType == TypeWithAnnotations.Boxed.Sentinel || (_lazyIteratorElementType is object && TypeSymbol.Equals(_lazyIteratorElementType.Value.Type, value.Type, TypeCompareKind.ConsiderEverything2))); Interlocked.CompareExchange(ref _lazyIteratorElementType, new TypeWithAnnotations.Boxed(value), TypeWithAnnotations.Boxed.Sentinel); } } internal override bool IsIterator => _lazyIteratorElementType is object; public override MethodKind MethodKind => MethodKind.LocalFunction; public sealed override Symbol ContainingSymbol => _containingSymbol; public override string Name => Syntax.Identifier.ValueText ?? ""; public SyntaxToken NameToken => Syntax.Identifier; internal override Binder SignatureBinder => _binder; public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations => ImmutableArray<MethodSymbol>.Empty; public override ImmutableArray<Location> Locations => ImmutableArray.Create(Syntax.Identifier.GetLocation()); internal override bool GenerateDebugInfo => true; public override ImmutableArray<CustomModifier> RefCustomModifiers => ImmutableArray<CustomModifier>.Empty; internal override CallingConvention CallingConvention => CallingConvention.Default; internal override OneOrMany<SyntaxList<AttributeListSyntax>> GetAttributeDeclarations() { return OneOrMany.Create(Syntax.AttributeLists); } protected override void NoteAttributesComplete(bool forReturnType) { } public override Symbol? AssociatedSymbol => null; public override Accessibility DeclaredAccessibility => ModifierUtils.EffectiveAccessibility(_declarationModifiers); public override bool IsAsync => (_declarationModifiers & DeclarationModifiers.Async) != 0; public override bool IsStatic => (_declarationModifiers & DeclarationModifiers.Static) != 0; public override bool IsVirtual => (_declarationModifiers & DeclarationModifiers.Virtual) != 0; public override bool IsOverride => (_declarationModifiers & DeclarationModifiers.Override) != 0; public override bool IsAbstract => (_declarationModifiers & DeclarationModifiers.Abstract) != 0; public override bool IsSealed => (_declarationModifiers & DeclarationModifiers.Sealed) != 0; public override bool IsExtern => (_declarationModifiers & DeclarationModifiers.Extern) != 0; public bool IsUnsafe => (_declarationModifiers & DeclarationModifiers.Unsafe) != 0; internal bool IsExpressionBodied => Syntax is { Body: null, ExpressionBody: object _ }; internal override bool IsDeclaredReadOnly => false; internal override bool IsInitOnly => false; internal override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) => false; internal override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) => false; internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { throw ExceptionUtilities.Unreachable; } internal override bool TryGetThisParameter(out ParameterSymbol? thisParameter) { // Local function symbols have no "this" parameter thisParameter = null; return true; } private void ReportAttributesDisallowed(SyntaxList<AttributeListSyntax> attributes, BindingDiagnosticBag diagnostics) { var diagnosticInfo = MessageID.IDS_FeatureLocalFunctionAttributes.GetFeatureAvailabilityDiagnosticInfo((CSharpParseOptions)syntaxReferenceOpt.SyntaxTree.Options); if (diagnosticInfo is object) { foreach (var attrList in attributes) { diagnostics.Add(diagnosticInfo, attrList.Location); } } } private ImmutableArray<SourceMethodTypeParameterSymbol> MakeTypeParameters(BindingDiagnosticBag diagnostics) { var result = ArrayBuilder<SourceMethodTypeParameterSymbol>.GetInstance(); var typeParameters = Syntax.TypeParameterList?.Parameters ?? default; for (int ordinal = 0; ordinal < typeParameters.Count; ordinal++) { var parameter = typeParameters[ordinal]; if (parameter.VarianceKeyword.Kind() != SyntaxKind.None) { diagnostics.Add(ErrorCode.ERR_IllegalVarianceSyntax, parameter.VarianceKeyword.GetLocation()); } ReportAttributesDisallowed(parameter.AttributeLists, diagnostics); var identifier = parameter.Identifier; var location = identifier.GetLocation(); var name = identifier.ValueText ?? ""; foreach (var @param in result) { if (name == @param.Name) { diagnostics.Add(ErrorCode.ERR_DuplicateTypeParameter, location, name); break; } } SourceMemberContainerTypeSymbol.ReportTypeNamedRecord(identifier.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, location); var tpEnclosing = ContainingSymbol.FindEnclosingTypeParameter(name); if ((object?)tpEnclosing != null) { ErrorCode typeError; if (tpEnclosing.ContainingSymbol.Kind == SymbolKind.Method) { // Type parameter '{0}' has the same name as the type parameter from outer method '{1}' typeError = ErrorCode.WRN_TypeParameterSameAsOuterMethodTypeParameter; } else { Debug.Assert(tpEnclosing.ContainingSymbol.Kind == SymbolKind.NamedType); // Type parameter '{0}' has the same name as the type parameter from outer type '{1}' typeError = ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter; } diagnostics.Add(typeError, location, name, tpEnclosing.ContainingSymbol); } var typeParameter = new SourceMethodTypeParameterSymbol( this, name, ordinal, ImmutableArray.Create(location), ImmutableArray.Create(parameter.GetReference())); result.Add(typeParameter); } return result.ToImmutableAndFree(); } public override ImmutableArray<ImmutableArray<TypeWithAnnotations>> GetTypeParameterConstraintTypes() { if (_lazyTypeParameterConstraintTypes.IsDefault) { GetTypeParameterConstraintKinds(); var syntax = Syntax; var diagnostics = BindingDiagnosticBag.GetInstance(_declarationDiagnostics); var constraints = this.MakeTypeParameterConstraintTypes( _binder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses, diagnostics); lock (_declarationDiagnostics) { if (_lazyTypeParameterConstraintTypes.IsDefault) { _declarationDiagnostics.AddRange(diagnostics); _lazyTypeParameterConstraintTypes = constraints; } } diagnostics.Free(); } return _lazyTypeParameterConstraintTypes; } public override ImmutableArray<TypeParameterConstraintKind> GetTypeParameterConstraintKinds() { if (_lazyTypeParameterConstraintKinds.IsDefault) { var syntax = Syntax; var constraints = this.MakeTypeParameterConstraintKinds( _binder, TypeParameters, syntax.TypeParameterList, syntax.ConstraintClauses); ImmutableInterlocked.InterlockedInitialize(ref _lazyTypeParameterConstraintKinds, constraints); } return _lazyTypeParameterConstraintKinds; } internal override bool IsNullableAnalysisEnabled() => throw ExceptionUtilities.Unreachable; public override int GetHashCode() { // this is what lambdas do (do not use hashes of other fields) return Syntax.GetHashCode(); } public sealed override bool Equals(Symbol symbol, TypeCompareKind compareKind) { if ((object)this == symbol) return true; var localFunction = symbol as LocalFunctionSymbol; return localFunction?.Syntax == Syntax; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Portable/Symbols/Source/LambdaSymbol.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 System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a method symbol for a lambda method. ''' </summary> Friend MustInherit Class LambdaSymbol Inherits MethodSymbol ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when we are interpreting ''' lambda's body in order to infer its return type. ''' </summary> Friend Shared ReadOnly ReturnTypeIsBeingInferred As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when we failed to ''' infer lambda's return type, but still want to interpret its body. ''' </summary> Friend Shared ReadOnly ReturnTypeIsUnknown As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when we are dealing with ''' query lambda and the return type should be taken from the target delegate upon ''' successful conversion. The LambdaSymbol will be mutated then. ''' </summary> Friend Shared ReadOnly ReturnTypePendingDelegate As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when System.Void is used in code. ''' </summary> Friend Shared ReadOnly ReturnTypeVoidReplacement As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as a sentinel while we are binding a lambda in error recovery mode. ''' </summary> Friend Shared ReadOnly ErrorRecoveryInferenceError As TypeSymbol = New ErrorTypeSymbol() Private ReadOnly _syntaxNode As SyntaxNode Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) ''' <summary> ''' Can mutate for a query lambda from ReturnTypePendingDelegate ''' to the return type of the target delegate. ''' </summary> Protected m_ReturnType As TypeSymbol ' The binder associated with the block containing this lambda Private ReadOnly _binder As Binder Protected Sub New( syntaxNode As SyntaxNode, parameters As ImmutableArray(Of BoundLambdaParameterSymbol), returnType As TypeSymbol, binder As Binder ) Debug.Assert(syntaxNode IsNot Nothing) Debug.Assert(returnType IsNot Nothing) _syntaxNode = syntaxNode _parameters = StaticCast(Of ParameterSymbol).From(parameters) m_ReturnType = returnType _binder = binder For Each param In parameters param.SetLambdaSymbol(Me) Next End Sub Public MustOverride ReadOnly Property SynthesizedKind As SynthesizedLambdaKind Friend NotOverridable Overrides ReadOnly Property IsQueryLambdaMethod As Boolean Get Return SynthesizedKind.IsQueryLambda End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return 0 End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return Cci.CallingConvention.Default End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _binder.ContainingMember End Get End Property Friend ReadOnly Property ContainingBinder As Binder Get Return _binder End Get End Property ''' <summary> ''' "Me" parameter for this lambda will be that of the containing symbol ''' </summary> Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean Debug.Assert(ContainingSymbol IsNot Nothing) Select Case ContainingSymbol.Kind Case SymbolKind.Field meParameter = DirectCast(ContainingSymbol, FieldSymbol).MeParameter Case SymbolKind.Property meParameter = DirectCast(ContainingSymbol, PropertySymbol).MeParameter Case SymbolKind.Method meParameter = DirectCast(ContainingSymbol, MethodSymbol).MeParameter Case Else meParameter = Nothing End Select Return True End Function Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Private End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Dim container As Symbol = ContainingSymbol Select Case container.Kind Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Method Return container.IsShared Case Else Return True End Select End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return m_ReturnType.IsVoidType() End Get End Property Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_syntaxNode.GetLocation()) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray.Create(_syntaxNode.GetReference()) End Get End Property Friend Overrides ReadOnly Property IsLambdaMethod As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.LambdaMethod End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return m_ReturnType End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return _syntaxNode End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get ' lambdas contain user code Return True End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Public Overrides Function Equals(obj As Object) As Boolean If obj Is Me Then Return True End If Dim symbol = TryCast(obj, LambdaSymbol) Return symbol IsNot Nothing AndAlso symbol._syntaxNode Is Me._syntaxNode AndAlso Equals(symbol.ContainingSymbol, Me.ContainingSymbol) AndAlso MethodSignatureComparer.AllAspectsSignatureComparer.Equals(symbol, Me) End Function Public Overrides Function GetHashCode() As Integer Dim hc As Integer = Hash.Combine(Me.Syntax.GetHashCode(), Me._parameters.Length) hc = Hash.Combine(hc, Me.ReturnType.GetHashCode()) For i = 0 To Me._parameters.Length - 1 hc = Hash.Combine(hc, Me._parameters(i).Type.GetHashCode()) Next Return hc 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.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a method symbol for a lambda method. ''' </summary> Friend MustInherit Class LambdaSymbol Inherits MethodSymbol ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when we are interpreting ''' lambda's body in order to infer its return type. ''' </summary> Friend Shared ReadOnly ReturnTypeIsBeingInferred As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when we failed to ''' infer lambda's return type, but still want to interpret its body. ''' </summary> Friend Shared ReadOnly ReturnTypeIsUnknown As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when we are dealing with ''' query lambda and the return type should be taken from the target delegate upon ''' successful conversion. The LambdaSymbol will be mutated then. ''' </summary> Friend Shared ReadOnly ReturnTypePendingDelegate As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as the return type of a LambdaSymbol when System.Void is used in code. ''' </summary> Friend Shared ReadOnly ReturnTypeVoidReplacement As TypeSymbol = New ErrorTypeSymbol() ''' <summary> ''' This symbol is used as a sentinel while we are binding a lambda in error recovery mode. ''' </summary> Friend Shared ReadOnly ErrorRecoveryInferenceError As TypeSymbol = New ErrorTypeSymbol() Private ReadOnly _syntaxNode As SyntaxNode Private ReadOnly _parameters As ImmutableArray(Of ParameterSymbol) ''' <summary> ''' Can mutate for a query lambda from ReturnTypePendingDelegate ''' to the return type of the target delegate. ''' </summary> Protected m_ReturnType As TypeSymbol ' The binder associated with the block containing this lambda Private ReadOnly _binder As Binder Protected Sub New( syntaxNode As SyntaxNode, parameters As ImmutableArray(Of BoundLambdaParameterSymbol), returnType As TypeSymbol, binder As Binder ) Debug.Assert(syntaxNode IsNot Nothing) Debug.Assert(returnType IsNot Nothing) _syntaxNode = syntaxNode _parameters = StaticCast(Of ParameterSymbol).From(parameters) m_ReturnType = returnType _binder = binder For Each param In parameters param.SetLambdaSymbol(Me) Next End Sub Public MustOverride ReadOnly Property SynthesizedKind As SynthesizedLambdaKind Friend NotOverridable Overrides ReadOnly Property IsQueryLambdaMethod As Boolean Get Return SynthesizedKind.IsQueryLambda End Get End Property Public Overrides ReadOnly Property Arity As Integer Get Return 0 End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return False End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Public Overrides ReadOnly Property AssociatedSymbol As Symbol Get Return Nothing End Get End Property Friend Overrides ReadOnly Property CallingConvention As Microsoft.Cci.CallingConvention Get Return Cci.CallingConvention.Default End Get End Property Public Overrides ReadOnly Property ContainingSymbol As Symbol Get Return _binder.ContainingMember End Get End Property Friend ReadOnly Property ContainingBinder As Binder Get Return _binder End Get End Property ''' <summary> ''' "Me" parameter for this lambda will be that of the containing symbol ''' </summary> Friend Overrides Function TryGetMeParameter(<Out> ByRef meParameter As ParameterSymbol) As Boolean Debug.Assert(ContainingSymbol IsNot Nothing) Select Case ContainingSymbol.Kind Case SymbolKind.Field meParameter = DirectCast(ContainingSymbol, FieldSymbol).MeParameter Case SymbolKind.Property meParameter = DirectCast(ContainingSymbol, PropertySymbol).MeParameter Case SymbolKind.Method meParameter = DirectCast(ContainingSymbol, MethodSymbol).MeParameter Case Else meParameter = Nothing End Select Return True End Function Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Accessibility.Private End Get End Property Public Overrides ReadOnly Property ExplicitInterfaceImplementations As ImmutableArray(Of MethodSymbol) Get Return ImmutableArray(Of MethodSymbol).Empty End Get End Property Public Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsExternalMethod As Boolean Get Return False End Get End Property Public Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend Overrides ReadOnly Property ReturnTypeMarshallingInformation As MarshalPseudoCustomAttributeData Get Return Nothing End Get End Property Friend Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Nothing End Get End Property Friend NotOverridable Overrides ReadOnly Property HasDeclarativeSecurity As Boolean Get Return False End Get End Property Friend NotOverridable Overrides Function GetSecurityInformation() As IEnumerable(Of Microsoft.Cci.SecurityAttribute) Throw ExceptionUtilities.Unreachable End Function Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverloads As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Dim container As Symbol = ContainingSymbol Select Case container.Kind Case SymbolKind.Field, SymbolKind.Property, SymbolKind.Method Return container.IsShared Case Else Return True End Select End Get End Property Public Overrides ReadOnly Property IsSub As Boolean Get Return m_ReturnType.IsVoidType() End Get End Property Public Overrides ReadOnly Property IsVararg As Boolean Get Return False End Get End Property Public NotOverridable Overrides ReadOnly Property IsInitOnly As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return ImmutableArray.Create(_syntaxNode.GetLocation()) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray.Create(_syntaxNode.GetReference()) End Get End Property Friend Overrides ReadOnly Property IsLambdaMethod As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property MethodKind As MethodKind Get Return MethodKind.LambdaMethod End Get End Property Friend NotOverridable Overrides ReadOnly Property IsMethodKindBasedOnSyntax As Boolean Get Return True End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return False End Get End Property Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return m_ReturnType End Get End Property Public Overrides ReadOnly Property ReturnTypeCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides ReadOnly Property Syntax As SyntaxNode Get Return _syntaxNode End Get End Property Public Overrides ReadOnly Property TypeArguments As ImmutableArray(Of TypeSymbol) Get Return ImmutableArray(Of TypeSymbol).Empty End Get End Property Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property Friend NotOverridable Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Nothing End Get End Property Friend Overrides Function IsMetadataNewSlot(Optional ignoreInterfaceImplementationChanges As Boolean = False) As Boolean Return False End Function Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get ' lambdas contain user code Return True End Get End Property Friend Overrides Function CalculateLocalSyntaxOffset(localPosition As Integer, localTree As SyntaxTree) As Integer Throw ExceptionUtilities.Unreachable End Function Public Overrides Function Equals(obj As Object) As Boolean If obj Is Me Then Return True End If Dim symbol = TryCast(obj, LambdaSymbol) Return symbol IsNot Nothing AndAlso symbol._syntaxNode Is Me._syntaxNode AndAlso Equals(symbol.ContainingSymbol, Me.ContainingSymbol) AndAlso MethodSignatureComparer.AllAspectsSignatureComparer.Equals(symbol, Me) End Function Public Overrides Function GetHashCode() As Integer Dim hc As Integer = Hash.Combine(Me.Syntax.GetHashCode(), Me._parameters.Length) hc = Hash.Combine(hc, Me.ReturnType.GetHashCode()) For i = 0 To Me._parameters.Length - 1 hc = Hash.Combine(hc, Me._parameters(i).Type.GetHashCode()) Next Return hc End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Portable/Symbols/SymbolVisitor`1.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.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicSymbolVisitor(Of TResult) Public Overridable Function Visit(symbol As Symbol) As TResult Return If(symbol Is Nothing, Nothing, symbol.Accept(Me)) End Function Public Overridable Function DefaultVisit(symbol As Symbol) As TResult Return Nothing End Function Public Overridable Function VisitAlias(symbol As AliasSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitArrayType(symbol As ArrayTypeSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitAssembly(symbol As AssemblySymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitEvent(symbol As EventSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitField(symbol As FieldSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitLabel(symbol As LabelSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitLocal(symbol As LocalSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitMethod(symbol As MethodSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitModule(symbol As ModuleSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitNamedType(symbol As NamedTypeSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitNamespace(symbol As NamespaceSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitParameter(symbol As ParameterSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitProperty(symbol As PropertySymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitRangeVariable(symbol As RangeVariableSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitTypeParameter(symbol As TypeParameterSymbol) As TResult Return DefaultVisit(symbol) 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.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic Friend MustInherit Class VisualBasicSymbolVisitor(Of TResult) Public Overridable Function Visit(symbol As Symbol) As TResult Return If(symbol Is Nothing, Nothing, symbol.Accept(Me)) End Function Public Overridable Function DefaultVisit(symbol As Symbol) As TResult Return Nothing End Function Public Overridable Function VisitAlias(symbol As AliasSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitArrayType(symbol As ArrayTypeSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitAssembly(symbol As AssemblySymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitEvent(symbol As EventSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitField(symbol As FieldSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitLabel(symbol As LabelSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitLocal(symbol As LocalSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitMethod(symbol As MethodSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitModule(symbol As ModuleSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitNamedType(symbol As NamedTypeSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitNamespace(symbol As NamespaceSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitParameter(symbol As ParameterSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitProperty(symbol As PropertySymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitRangeVariable(symbol As RangeVariableSymbol) As TResult Return DefaultVisit(symbol) End Function Public Overridable Function VisitTypeParameter(symbol As TypeParameterSymbol) As TResult Return DefaultVisit(symbol) End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/CodeStyle/Core/CodeFixes/FormattingCodeFixProvider.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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; using Formatter = Microsoft.CodeAnalysis.Formatting.FormatterHelper; #endif namespace Microsoft.CodeAnalysis.CodeStyle { using ISyntaxFormattingService = ISyntaxFormattingService; internal abstract class AbstractFormattingCodeFixProvider : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.FormattingDiagnosticId); protected abstract ISyntaxFormattingService SyntaxFormattingService { get; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix( CodeAction.Create( CodeStyleResources.Fix_formatting, c => FixOneAsync(context, diagnostic, c), nameof(AbstractFormattingCodeFixProvider)), diagnostic); } return Task.CompletedTask; } private async Task<Document> FixOneAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken) { var options = await GetOptionsAsync(context.Document, cancellationToken).ConfigureAwait(false); var tree = await context.Document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var updatedTree = await FormattingCodeFixHelper.FixOneAsync(tree, SyntaxFormattingService, options, diagnostic, cancellationToken).ConfigureAwait(false); return context.Document.WithText(await updatedTree.GetTextAsync(cancellationToken).ConfigureAwait(false)); } private static async Task<OptionSet> GetOptionsAsync(Document document, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var analyzerConfigOptions = document.Project.AnalyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(tree); return analyzerConfigOptions; } public sealed override FixAllProvider GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => { var cancellationToken = context.CancellationToken; var options = await GetOptionsAsync(document, cancellationToken).ConfigureAwait(false); var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var updatedSyntaxRoot = Formatter.Format(syntaxRoot, this.SyntaxFormattingService, options, cancellationToken); return document.WithSyntaxRoot(updatedSyntaxRoot); }); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Formatting; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; using Formatter = Microsoft.CodeAnalysis.Formatting.FormatterHelper; #endif namespace Microsoft.CodeAnalysis.CodeStyle { using ISyntaxFormattingService = ISyntaxFormattingService; internal abstract class AbstractFormattingCodeFixProvider : CodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.FormattingDiagnosticId); protected abstract ISyntaxFormattingService SyntaxFormattingService { get; } public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { foreach (var diagnostic in context.Diagnostics) { context.RegisterCodeFix( CodeAction.Create( CodeStyleResources.Fix_formatting, c => FixOneAsync(context, diagnostic, c), nameof(AbstractFormattingCodeFixProvider)), diagnostic); } return Task.CompletedTask; } private async Task<Document> FixOneAsync(CodeFixContext context, Diagnostic diagnostic, CancellationToken cancellationToken) { var options = await GetOptionsAsync(context.Document, cancellationToken).ConfigureAwait(false); var tree = await context.Document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var updatedTree = await FormattingCodeFixHelper.FixOneAsync(tree, SyntaxFormattingService, options, diagnostic, cancellationToken).ConfigureAwait(false); return context.Document.WithText(await updatedTree.GetTextAsync(cancellationToken).ConfigureAwait(false)); } private static async Task<OptionSet> GetOptionsAsync(Document document, CancellationToken cancellationToken) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var analyzerConfigOptions = document.Project.AnalyzerOptions.AnalyzerConfigOptionsProvider.GetOptions(tree); return analyzerConfigOptions; } public sealed override FixAllProvider GetFixAllProvider() => FixAllProvider.Create(async (context, document, diagnostics) => { var cancellationToken = context.CancellationToken; var options = await GetOptionsAsync(document, cancellationToken).ConfigureAwait(false); var syntaxRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var updatedSyntaxRoot = Formatter.Format(syntaxRoot, this.SyntaxFormattingService, options, cancellationToken); return document.WithSyntaxRoot(updatedSyntaxRoot); }); } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/VisualBasic/Portable/GenerateConstructor/GenerateConstructorCodeFixProvider.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.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateConstructor Friend Class GenerateConstructorDiagnosticIds Friend Const BC30057 As String = NameOf(BC30057) ' error BC30057: Too many arguments to 'Public Sub New()'. Friend Const BC30272 As String = NameOf(BC30272) ' error BC30272: 'p' is not a parameter of 'Public Sub New()'. Friend Const BC30274 As String = NameOf(BC30274) ' error BC30274: Parameter 'prop' of 'Public Sub New(prop As String)' already has a matching argument. Friend Const BC30311 As String = NameOf(BC30311) ' error BC30311: Value of type 'String' cannot be converted to 'Exception'. Friend Const BC30389 As String = NameOf(BC30389) ' error BC30389: 'x' is not accessible in this context Friend Const BC30455 As String = NameOf(BC30455) ' error BC30455: Argument not specified for parameter 'x' of 'Public Sub New(x As Integer)'. Friend Const BC30512 As String = NameOf(BC30512) ' error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Friend Const BC32006 As String = NameOf(BC32006) ' error BC32006: 'Char' values cannot be converted to 'Integer'. Friend Const BC30387 As String = NameOf(BC30387) ' error BC32006: Class 'Derived' must declare a 'Sub New' because its base class 'Base' does not have an accessible 'Sub New' that can be called with no arguments. Friend Const BC30516 As String = NameOf(BC30516) ' error BC30516: Overload resolution failed because no accessible 'Blah' accepts this number of arguments. Friend Const BC36625 As String = NameOf(BC36625) ' error BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. Friend Shared ReadOnly AllDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30057, BC30272, BC30274, BC30389, BC30455, BC32006, BC30512, BC30387, BC30516) Friend Shared ReadOnly TooManyArgumentsDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30057) Friend Shared ReadOnly CannotConvertDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30512, BC32006, BC30311, BC36625) End Class <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateConstructor), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.FullyQualify)> Friend Class GenerateConstructorCodeFixProvider Inherits AbstractGenerateMemberCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return GenerateConstructorDiagnosticIds.AllDiagnosticIds.Concat(GenerateConstructorDiagnosticIds.TooManyArgumentsDiagnosticIds) End Get End Property Protected Overrides Function GetCodeActionsAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of CodeAction)) Dim service = document.GetLanguageService(Of IGenerateConstructorService)() Return service.GenerateConstructorAsync(document, node, cancellationToken) End Function Protected Overrides Function GetTargetNode(node As SyntaxNode) As SyntaxNode Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing AndAlso invocation.Expression IsNot Nothing Then Return GetRightmostName(invocation.Expression) End If Dim objectCreation = TryCast(node, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing AndAlso objectCreation.Type IsNot Nothing Then Return objectCreation.Type.GetRightmostName() End If Dim attribute = TryCast(node, AttributeSyntax) If attribute IsNot Nothing Then Return attribute.Name End If Return node End Function Protected Overrides Function IsCandidate(node As SyntaxNode, token As SyntaxToken, diagnostic As Diagnostic) As Boolean Return TypeOf node Is InvocationExpressionSyntax OrElse TypeOf node Is ObjectCreationExpressionSyntax OrElse TypeOf node Is AttributeSyntax 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.Composition Imports System.Diagnostics.CodeAnalysis Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.CodeFixes.GenerateMember Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.GenerateConstructor Friend Class GenerateConstructorDiagnosticIds Friend Const BC30057 As String = NameOf(BC30057) ' error BC30057: Too many arguments to 'Public Sub New()'. Friend Const BC30272 As String = NameOf(BC30272) ' error BC30272: 'p' is not a parameter of 'Public Sub New()'. Friend Const BC30274 As String = NameOf(BC30274) ' error BC30274: Parameter 'prop' of 'Public Sub New(prop As String)' already has a matching argument. Friend Const BC30311 As String = NameOf(BC30311) ' error BC30311: Value of type 'String' cannot be converted to 'Exception'. Friend Const BC30389 As String = NameOf(BC30389) ' error BC30389: 'x' is not accessible in this context Friend Const BC30455 As String = NameOf(BC30455) ' error BC30455: Argument not specified for parameter 'x' of 'Public Sub New(x As Integer)'. Friend Const BC30512 As String = NameOf(BC30512) ' error BC30512: Option Strict On disallows implicit conversions from 'Object' to 'Integer'. Friend Const BC32006 As String = NameOf(BC32006) ' error BC32006: 'Char' values cannot be converted to 'Integer'. Friend Const BC30387 As String = NameOf(BC30387) ' error BC32006: Class 'Derived' must declare a 'Sub New' because its base class 'Base' does not have an accessible 'Sub New' that can be called with no arguments. Friend Const BC30516 As String = NameOf(BC30516) ' error BC30516: Overload resolution failed because no accessible 'Blah' accepts this number of arguments. Friend Const BC36625 As String = NameOf(BC36625) ' error BC36625: Lambda expression cannot be converted to 'Integer' because 'Integer' is not a delegate type. Friend Shared ReadOnly AllDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30057, BC30272, BC30274, BC30389, BC30455, BC32006, BC30512, BC30387, BC30516) Friend Shared ReadOnly TooManyArgumentsDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30057) Friend Shared ReadOnly CannotConvertDiagnosticIds As ImmutableArray(Of String) = ImmutableArray.Create(BC30512, BC32006, BC30311, BC36625) End Class <ExportCodeFixProvider(LanguageNames.VisualBasic, Name:=PredefinedCodeFixProviderNames.GenerateConstructor), [Shared]> <ExtensionOrder(After:=PredefinedCodeFixProviderNames.FullyQualify)> Friend Class GenerateConstructorCodeFixProvider Inherits AbstractGenerateMemberCodeFixProvider <ImportingConstructor> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New() End Sub Public Overrides ReadOnly Property FixableDiagnosticIds As ImmutableArray(Of String) Get Return GenerateConstructorDiagnosticIds.AllDiagnosticIds.Concat(GenerateConstructorDiagnosticIds.TooManyArgumentsDiagnosticIds) End Get End Property Protected Overrides Function GetCodeActionsAsync(document As Document, node As SyntaxNode, cancellationToken As CancellationToken) As Task(Of ImmutableArray(Of CodeAction)) Dim service = document.GetLanguageService(Of IGenerateConstructorService)() Return service.GenerateConstructorAsync(document, node, cancellationToken) End Function Protected Overrides Function GetTargetNode(node As SyntaxNode) As SyntaxNode Dim invocation = TryCast(node, InvocationExpressionSyntax) If invocation IsNot Nothing AndAlso invocation.Expression IsNot Nothing Then Return GetRightmostName(invocation.Expression) End If Dim objectCreation = TryCast(node, ObjectCreationExpressionSyntax) If objectCreation IsNot Nothing AndAlso objectCreation.Type IsNot Nothing Then Return objectCreation.Type.GetRightmostName() End If Dim attribute = TryCast(node, AttributeSyntax) If attribute IsNot Nothing Then Return attribute.Name End If Return node End Function Protected Overrides Function IsCandidate(node As SyntaxNode, token As SyntaxToken, diagnostic As Diagnostic) As Boolean Return TypeOf node Is InvocationExpressionSyntax OrElse TypeOf node Is ObjectCreationExpressionSyntax OrElse TypeOf node Is AttributeSyntax End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/CodeFixes/FixAllContextHelper.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.Concurrent; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { internal static class FixAllContextExtensions { public static IProgressTracker GetProgressTracker(this FixAllContext context) { #if CODE_STYLE return NoOpProgressTracker.Instance; #else return context.ProgressTracker; #endif } } internal static class FixAllContextHelper { public static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(FixAllContext fixAllContext) { var cancellationToken = fixAllContext.CancellationToken; var allDiagnostics = ImmutableArray<Diagnostic>.Empty; var document = fixAllContext.Document; var project = fixAllContext.Project; var progressTracker = fixAllContext.GetProgressTracker(); switch (fixAllContext.Scope) { case FixAllScope.Document: if (document != null && !await document.IsGeneratedCodeAsync(cancellationToken).ConfigureAwait(false)) { var documentDiagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false); return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty.SetItem(document, documentDiagnostics); } break; case FixAllScope.Project: allDiagnostics = await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false); break; case FixAllScope.Solution: var projectsToFix = project.Solution.Projects .Where(p => p.Language == project.Language) .ToImmutableArray(); // Update the progress dialog with the count of projects to actually fix. We'll update the progress // bar as we get all the documents in AddDocumentDiagnosticsAsync. progressTracker.AddItems(projectsToFix.Length); var diagnostics = new ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>>(); using (var _ = ArrayBuilder<Task>.GetInstance(projectsToFix.Length, out var tasks)) { foreach (var projectToFix in projectsToFix) tasks.Add(Task.Run(async () => await AddDocumentDiagnosticsAsync(diagnostics, projectToFix).ConfigureAwait(false), cancellationToken)); await Task.WhenAll(tasks).ConfigureAwait(false); allDiagnostics = allDiagnostics.AddRange(diagnostics.SelectMany(i => i.Value)); } break; } if (allDiagnostics.IsEmpty) { return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty; } return await GetDocumentDiagnosticsToFixAsync( fixAllContext.Solution, allDiagnostics, fixAllContext.CancellationToken).ConfigureAwait(false); async Task AddDocumentDiagnosticsAsync(ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>> diagnostics, Project projectToFix) { try { var projectDiagnostics = await fixAllContext.GetAllDiagnosticsAsync(projectToFix).ConfigureAwait(false); diagnostics.TryAdd(projectToFix.Id, projectDiagnostics); } finally { progressTracker.ItemCompleted(); } } } private static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync( Solution solution, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var builder = ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>(); foreach (var (document, diagnosticsForDocument) in diagnostics.GroupBy(d => solution.GetDocument(d.Location.SourceTree))) { if (document is null) continue; cancellationToken.ThrowIfCancellationRequested(); if (!await document.IsGeneratedCodeAsync(cancellationToken).ConfigureAwait(false)) { builder.Add(document, diagnosticsForDocument.ToImmutableArray()); } } return builder.ToImmutable(); } public static string GetDefaultFixAllTitle(FixAllContext fixAllContext) => GetDefaultFixAllTitle(fixAllContext.Scope, fixAllContext.DiagnosticIds, fixAllContext.Document, fixAllContext.Project); public static string GetDefaultFixAllTitle( FixAllScope fixAllScope, ImmutableHashSet<string> diagnosticIds, Document? triggerDocument, Project triggerProject) { var diagnosticId = diagnosticIds.First(); return fixAllScope switch { FixAllScope.Custom => string.Format(WorkspaceExtensionsResources.Fix_all_0, diagnosticId), FixAllScope.Document => string.Format(WorkspaceExtensionsResources.Fix_all_0_in_1, diagnosticId, triggerDocument!.Name), FixAllScope.Project => string.Format(WorkspaceExtensionsResources.Fix_all_0_in_1, diagnosticId, triggerProject.Name), FixAllScope.Solution => string.Format(WorkspaceExtensionsResources.Fix_all_0_in_Solution, diagnosticId), _ => throw ExceptionUtilities.UnexpectedValue(fixAllScope), }; } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { internal static class FixAllContextExtensions { public static IProgressTracker GetProgressTracker(this FixAllContext context) { #if CODE_STYLE return NoOpProgressTracker.Instance; #else return context.ProgressTracker; #endif } } internal static class FixAllContextHelper { public static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(FixAllContext fixAllContext) { var cancellationToken = fixAllContext.CancellationToken; var allDiagnostics = ImmutableArray<Diagnostic>.Empty; var document = fixAllContext.Document; var project = fixAllContext.Project; var progressTracker = fixAllContext.GetProgressTracker(); switch (fixAllContext.Scope) { case FixAllScope.Document: if (document != null && !await document.IsGeneratedCodeAsync(cancellationToken).ConfigureAwait(false)) { var documentDiagnostics = await fixAllContext.GetDocumentDiagnosticsAsync(document).ConfigureAwait(false); return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty.SetItem(document, documentDiagnostics); } break; case FixAllScope.Project: allDiagnostics = await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false); break; case FixAllScope.Solution: var projectsToFix = project.Solution.Projects .Where(p => p.Language == project.Language) .ToImmutableArray(); // Update the progress dialog with the count of projects to actually fix. We'll update the progress // bar as we get all the documents in AddDocumentDiagnosticsAsync. progressTracker.AddItems(projectsToFix.Length); var diagnostics = new ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>>(); using (var _ = ArrayBuilder<Task>.GetInstance(projectsToFix.Length, out var tasks)) { foreach (var projectToFix in projectsToFix) tasks.Add(Task.Run(async () => await AddDocumentDiagnosticsAsync(diagnostics, projectToFix).ConfigureAwait(false), cancellationToken)); await Task.WhenAll(tasks).ConfigureAwait(false); allDiagnostics = allDiagnostics.AddRange(diagnostics.SelectMany(i => i.Value)); } break; } if (allDiagnostics.IsEmpty) { return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty; } return await GetDocumentDiagnosticsToFixAsync( fixAllContext.Solution, allDiagnostics, fixAllContext.CancellationToken).ConfigureAwait(false); async Task AddDocumentDiagnosticsAsync(ConcurrentDictionary<ProjectId, ImmutableArray<Diagnostic>> diagnostics, Project projectToFix) { try { var projectDiagnostics = await fixAllContext.GetAllDiagnosticsAsync(projectToFix).ConfigureAwait(false); diagnostics.TryAdd(projectToFix.Id, projectDiagnostics); } finally { progressTracker.ItemCompleted(); } } } private static async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync( Solution solution, ImmutableArray<Diagnostic> diagnostics, CancellationToken cancellationToken) { var builder = ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>(); foreach (var (document, diagnosticsForDocument) in diagnostics.GroupBy(d => solution.GetDocument(d.Location.SourceTree))) { if (document is null) continue; cancellationToken.ThrowIfCancellationRequested(); if (!await document.IsGeneratedCodeAsync(cancellationToken).ConfigureAwait(false)) { builder.Add(document, diagnosticsForDocument.ToImmutableArray()); } } return builder.ToImmutable(); } public static string GetDefaultFixAllTitle(FixAllContext fixAllContext) => GetDefaultFixAllTitle(fixAllContext.Scope, fixAllContext.DiagnosticIds, fixAllContext.Document, fixAllContext.Project); public static string GetDefaultFixAllTitle( FixAllScope fixAllScope, ImmutableHashSet<string> diagnosticIds, Document? triggerDocument, Project triggerProject) { var diagnosticId = diagnosticIds.First(); return fixAllScope switch { FixAllScope.Custom => string.Format(WorkspaceExtensionsResources.Fix_all_0, diagnosticId), FixAllScope.Document => string.Format(WorkspaceExtensionsResources.Fix_all_0_in_1, diagnosticId, triggerDocument!.Name), FixAllScope.Project => string.Format(WorkspaceExtensionsResources.Fix_all_0_in_1, diagnosticId, triggerProject.Name), FixAllScope.Solution => string.Format(WorkspaceExtensionsResources.Fix_all_0_in_Solution, diagnosticId), _ => throw ExceptionUtilities.UnexpectedValue(fixAllScope), }; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Portable/Emit/NoPia/EmbeddedParameter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols #If Not DEBUG Then Imports ParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.ParameterSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedParameter Inherits EmbeddedTypesManager.CommonEmbeddedParameter Public Sub New(containingPropertyOrMethod As EmbeddedTypesManager.CommonEmbeddedMember, underlyingParameter As ParameterSymbolAdapter) MyBase.New(containingPropertyOrMethod, underlyingParameter) Debug.Assert(underlyingParameter.AdaptedParameterSymbol.IsDefinition) End Sub Protected Overrides Function GetCustomAttributesToEmit(moduleBuilder As PEModuleBuilder) As IEnumerable(Of VisualBasicAttributeData) Return UnderlyingParameter.AdaptedParameterSymbol.GetCustomAttributesToEmit(moduleBuilder.CompilationState) End Function Protected Overrides ReadOnly Property HasDefaultValue As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.HasMetadataConstantValue End Get End Property Protected Overrides Function GetDefaultValue(context As EmitContext) As MetadataConstant Return UnderlyingParameter.GetMetadataConstantValue(context) End Function Protected Overrides ReadOnly Property IsIn As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMetadataIn End Get End Property Protected Overrides ReadOnly Property IsOut As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMetadataOut End Get End Property Protected Overrides ReadOnly Property IsOptional As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMetadataOptional End Get End Property Protected Overrides ReadOnly Property IsMarshalledExplicitly As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMarshalledExplicitly End Get End Property Protected Overrides ReadOnly Property MarshallingInformation As Cci.IMarshallingInformation Get Return UnderlyingParameter.AdaptedParameterSymbol.MarshallingInformation End Get End Property Protected Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte) Get Return UnderlyingParameter.AdaptedParameterSymbol.MarshallingDescriptor End Get End Property Protected Overrides ReadOnly Property Name As String Get Return UnderlyingParameter.AdaptedParameterSymbol.MetadataName End Get End Property Protected Overrides ReadOnly Property UnderlyingParameterTypeInformation As Cci.IParameterTypeInformation Get Return DirectCast(UnderlyingParameter, Cci.IParameterTypeInformation) End Get End Property Protected Overrides ReadOnly Property Index As UShort Get Return CUShort(UnderlyingParameter.AdaptedParameterSymbol.Ordinal) End Get End Property End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.CodeGen Imports Microsoft.CodeAnalysis.Emit Imports Microsoft.CodeAnalysis.VisualBasic.Symbols #If Not DEBUG Then Imports ParameterSymbolAdapter = Microsoft.CodeAnalysis.VisualBasic.Symbols.ParameterSymbol #End If Namespace Microsoft.CodeAnalysis.VisualBasic.Emit.NoPia Friend NotInheritable Class EmbeddedParameter Inherits EmbeddedTypesManager.CommonEmbeddedParameter Public Sub New(containingPropertyOrMethod As EmbeddedTypesManager.CommonEmbeddedMember, underlyingParameter As ParameterSymbolAdapter) MyBase.New(containingPropertyOrMethod, underlyingParameter) Debug.Assert(underlyingParameter.AdaptedParameterSymbol.IsDefinition) End Sub Protected Overrides Function GetCustomAttributesToEmit(moduleBuilder As PEModuleBuilder) As IEnumerable(Of VisualBasicAttributeData) Return UnderlyingParameter.AdaptedParameterSymbol.GetCustomAttributesToEmit(moduleBuilder.CompilationState) End Function Protected Overrides ReadOnly Property HasDefaultValue As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.HasMetadataConstantValue End Get End Property Protected Overrides Function GetDefaultValue(context As EmitContext) As MetadataConstant Return UnderlyingParameter.GetMetadataConstantValue(context) End Function Protected Overrides ReadOnly Property IsIn As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMetadataIn End Get End Property Protected Overrides ReadOnly Property IsOut As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMetadataOut End Get End Property Protected Overrides ReadOnly Property IsOptional As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMetadataOptional End Get End Property Protected Overrides ReadOnly Property IsMarshalledExplicitly As Boolean Get Return UnderlyingParameter.AdaptedParameterSymbol.IsMarshalledExplicitly End Get End Property Protected Overrides ReadOnly Property MarshallingInformation As Cci.IMarshallingInformation Get Return UnderlyingParameter.AdaptedParameterSymbol.MarshallingInformation End Get End Property Protected Overrides ReadOnly Property MarshallingDescriptor As ImmutableArray(Of Byte) Get Return UnderlyingParameter.AdaptedParameterSymbol.MarshallingDescriptor End Get End Property Protected Overrides ReadOnly Property Name As String Get Return UnderlyingParameter.AdaptedParameterSymbol.MetadataName End Get End Property Protected Overrides ReadOnly Property UnderlyingParameterTypeInformation As Cci.IParameterTypeInformation Get Return DirectCast(UnderlyingParameter, Cci.IParameterTypeInformation) End Get End Property Protected Overrides ReadOnly Property Index As UShort Get Return CUShort(UnderlyingParameter.AdaptedParameterSymbol.Ordinal) End Get End Property End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Test2/Rename/InlineRenameTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class InlineRenameTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> object [|$$test|] = new object(); var other = [|test|]; </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "renamed") session.Commit() Await VerifyTagsAreCorrect(workspace, "renamedtest") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { C _ = null; System.Func<int, string, int> f = (int _, string [|$$_|]) => { _ = null; return 1; }; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="_", renameTextPrefix:="change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(46208, "https://github.com/dotnet/roslyn/issues/46208")> Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|Test1$$|] { } ]]></Document> </Project> </Workspace>, host) Dim options = workspace.CurrentSolution.Options workspace.TryApplyChanges( workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True))) Dim session = StartSession(workspace) Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' User could use copy & paste to enter invalid character textBuffer.Insert(selectedSpan, "<>") session.Commit() Await VerifyTagsAreCorrect(workspace, "Test1<>") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")> Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> [|$$x|]) { foreach (var (y1, y2) in [|x|]) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "x", "change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } var (z1, z2) = this; [|Deconstruct|](out var t1, out var t2); } void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "Deconstruct", "Changed", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(540120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540120")> Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace, originalTextToRename As String, renameTextPrefix As String, Optional renameOverloads As Boolean = False, Optional renameInStrings As Boolean = False, Optional renameInComments As Boolean = False, Optional renameFile As Boolean = False, Optional fileToRename As DocumentId = Nothing) As Task Dim optionSet = workspace.Options optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments) optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim session = StartSession(workspace) ' Type a bit in the file Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix) Dim replacementText = renameTextPrefix + originalTextToRename Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, replacementText) session.Commit() Await VerifyTagsAreCorrect(workspace, replacementText) If renameFile Then If fileToRename Is Nothing Then VerifyFileName(workspace, replacementText) Else VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText) End If End If End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/13186")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public void [|$$goo|]() { [|goo|](); } public void [|goo|]&lt;T&gt;() { [|goo|]&lt;T&gt;(); } public void [|goo|](int i) { [|goo|](i); } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Imports System.Linq Imports System Public Class Program Sub Main(args As String()) End Sub Public Sub [|$$goo|]() [|goo|]() End Sub Public Sub [|goo|](of T)() [|goo|](of T)() End Sub Public Sub [|goo|](s As String) [|goo|](s) End Sub Public Shared Sub [|goo|](d As Double) [|goo|](d) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(960955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960955")> Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Program Sub Main([|$$args|] As String()) End Sub End Class </Document> <Document> ' args </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "args", "bar", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "Test1.vb")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) ' https://github.com/dotnet/roslyn/issues/36075 ' VerifyFileRename(workspace, "ABC") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class [|$$C|] { } // [|C|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|C|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { private void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // F ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { public void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // [|F|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3623, "https://github.com/dotnet/roslyn/issues/3623")> Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"><![CDATA[ public class [|$$C|] { } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB") Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.goo(System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void [|goo|](int i) { [|goo|](i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "[|goo|]"; var b = $"{1}[|goo|]{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.goo(System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub [|goo|](i As Integer) [|goo|](i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "[|goo|]" Dim b = $"{1}[|goo|]{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub SimpleEditAndCancel(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim initialTextSnapshot = textBuffer.CurrentSnapshot textBuffer.Insert(caretPosition, "Bar") session.Cancel() ' Assert the file is what it started as Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText()) ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <WorkItem(539513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539513")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$dynamic|] { void M() { [|dynamic|] d; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "goo") session.Commit() Await VerifyTagsAreCorrect(workspace, "goodynamic") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ReadOnlyRegionsCreated(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$C { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.False(buffer.IsReadOnly(cursorPosition)) Assert.False(buffer.IsReadOnly(cursorPosition + 1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) ' Make sure we can't type at the start or end Assert.True(buffer.IsReadOnly(0)) Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length)) session.Cancel() ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543018")> Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$C c; class C { }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Assert.False(buffer.IsReadOnly(0)) Assert.False(buffer.IsReadOnly(1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) session.Cancel() VerifyFileName(workspace, "Test1.cs") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class AAAA { public abstract void [|Goo|](); } class BBBB : AAAA { public override void [|Goo|]() { } } class DDDD : BBBB { public override void [|Goo|]() { } } class CCCC : AAAA { public override void [|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="GooBar") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530467")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(579210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579210")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530765")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarGoo") session.Cancel() Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") textBuffer.Insert(caretPosition, "Baz") Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1) End Using End Function <WpfTheory, WorkItem(978099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/978099")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) ' Preview should not return null Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = False Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title) Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, "Goo", "BarGoo"), previewService.Description) Assert.Equal("Goo", previewService.TopLevelName) Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = True Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) ' Session should still be up; type some more caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Insert(caretPosition, "Cat") previewService.ReturnsNull = False previewService.Called = False session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "CatBarGoo") Assert.True(previewService.Called) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Sub [|M$$|]() End Sub Sub Test() #If Proj1 Then [|M|]() #End If #If Proj2 Then [|M|]() #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "o") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mo") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mow") session.Commit() Await VerifyTagsAreCorrect(workspace, "Mow") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Dim [|m$$|] As Integer Sub Test() #If Proj1 Then Dim x = [|m|] #End If #If Proj2 Then Dim x = [|m|] #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "ma") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "maw") session.Commit() Await VerifyTagsAreCorrect(workspace, "maw") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(554, "https://github.com/dotnet/roslyn/issues/554")> Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { void M() { var z = {|introducelocal:5 + 5|}; var q = [|x$$|]; } int [|x|]; }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "yz") Await WaitForRename(workspace) ' Invoke a CodeAction Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider() Dim actions = New List(Of CodeAction) Dim context = New CodeRefactoringContext( workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), workspace.Documents.Single().AnnotatedSpans()("introducelocal").Single(), Sub(a) actions.Add(a), CancellationToken.None) workspace.Documents.Single().AnnotatedSpans.Clear() introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService) Dim actualSeverity As NotificationSeverity = Nothing Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback) notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity editHandler.Apply( workspace, workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None), "unused", New ProgressTracker(), CancellationToken.None) ' CodeAction should be rejected Assert.Equal(NotificationSeverity.Error, actualSeverity) Assert.Equal(" class C { void M() { var z = 5 + 5; var q = xyz; } int xyz; }", textBuffer.CurrentSnapshot.GetText()) ' Rename should still be active Await VerifyTagsAreCorrect(workspace, "xyz") textBuffer.Insert(caretPosition + 2, "q") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "xyzq") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof([|M|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$M|]() { nameof([|M|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "M", "Sa", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3316, "https://github.com/dotnet/roslyn/issues/3316")> Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task ' Everything on the last line of main is parsed as a single invocation expression ' with CType(...) as the receiver and everything else as arguments. ' Rename doesn't expect to see CType as the receiver of an invocation. Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3} Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)( CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing) End Sub End Module </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "q") session.Commit() Await VerifyTagsAreCorrect(workspace, "qp") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(2445, "https://github.com/dotnet/roslyn/issues/2445")> Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x; x = 2; void [|$$M|]() { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "x") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(9117, "https://github.com/dotnet/roslyn/issues/9117")> Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class1 Public Property [|$$Field1|] As Integer End Class Public Class Class2 Public Shared Property DataSource As IEnumerable(Of Class1) Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = ( From data In DataSource Group By data.Field1 Into Group1 = Group ).ToDictionary( Function(group) group.Field1, Function(group) group.Group1) End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "xield1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(14554, "https://github.com/dotnet/roslyn/issues/14554")> Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub New(a As Action) End Sub Public ReadOnly Property Vm As C Public ReadOnly Property Crash As New C(Sub() Vm.Sav() End Sub) Public Function Sav$$() As Boolean Return False End Function Public Function Save() As Boolean Return False End Function End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Ensure the rename doesn't crash textBuffer.Insert(caretPosition, "e") session.Commit() End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Goo|] { void Blah() { } } </Document> <Document> partial class Goo { void BlahBlah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Test1|] { void Blah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { } } class Test2 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { } } class Test1 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$Test1|] { One, Two, Three } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|$$Test1|] { void Blah(); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyUnsupportedFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface Test1 { void [|$$Blah|](); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) ' Disable document changes to make sure file rename is not supported. ' Linked workspace files will report that applying changes to document ' info is not allowed; this is intended to mimic that behavior ' and make sure inline rename works as intended. workspace.CanApplyChangeDocument = False Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "t") session.Commit() VerifyFileName(workspace, "test1") End Using End Sub <WpfTheory, WorkItem(36063, "https://github.com/dotnet/roslyn/issues/36063")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") textBuffer.Delete(New Span(caretPosition, "Bar".Length)) Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False) Assert.False(committed) Await VerifyTagsAreCorrect(workspace, "Test1") End Using End Function <WpfTheory, WorkItem(44576, "https://github.com/dotnet/roslyn/issues/44576")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test1 { void Blah() { [|$$Test2|] t2 = new [|Test2|](); } } </Document> <Document Name="Test2.cs"> class Test2 { } </Document> </Project> </Workspace>, host) Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = "Test2.cs") Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="Test2", renameTextPrefix:="Test2Changed", renameFile:=True, fileToRename:=docToRename.Id) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:[|C|].#ctor")] class [|C|] { public [|$$C|]() { } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "D") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a); class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g = new [|Goo|](1); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class C { void M() { _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ; } public C [|$$Goo|] { get; set; } public C Other { get; set; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameInComment(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class [|$$MyClass|] { /// <summary> /// Initializes <see cref="MyClass"/>; /// </summary> MyClass() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) session.ApplyReplacementText("Example", True) session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True) session.Commit() Await VerifyTagsAreCorrect(workspace, "Example") End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Threading Imports Microsoft.CodeAnalysis.CodeActions Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.Host Imports Microsoft.CodeAnalysis.Editor.UnitTests.RenameTracking Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces Imports Microsoft.CodeAnalysis.IntroduceVariable Imports Microsoft.CodeAnalysis.Notification Imports Microsoft.CodeAnalysis.Options Imports Microsoft.CodeAnalysis.Remote.Testing Imports Microsoft.CodeAnalysis.Rename Imports Microsoft.CodeAnalysis.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename <[UseExportProvider]> Public Class InlineRenameTests Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper Public Sub New(outputHelper As Abstractions.ITestOutputHelper) _outputHelper = outputHelper End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function SimpleEditAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLocalVariableInTopLevelStatement(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> object [|$$test|] = new object(); var other = [|test|]; </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "renamed") session.Commit() Await VerifyTagsAreCorrect(workspace, "renamedtest") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameLambdaDiscard(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class C { void M() { C _ = null; System.Func<int, string, int> f = (int _, string [|$$_|]) => { _ = null; return 1; }; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="_", renameTextPrefix:="change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(46208, "https://github.com/dotnet/roslyn/issues/46208")> Public Async Function RenameWithInvalidIdentifier(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ class [|Test1$$|] { } ]]></Document> </Project> </Workspace>, host) Dim options = workspace.CurrentSolution.Options workspace.TryApplyChanges( workspace.CurrentSolution.WithOptions(options.WithChangedOption(RenameOptions.RenameFile, True))) Dim session = StartSession(workspace) Dim selectedSpan = workspace.DocumentWithCursor.CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' User could use copy & paste to enter invalid character textBuffer.Insert(selectedSpan, "<>") session.Commit() Await VerifyTagsAreCorrect(workspace, "Test1<>") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(22495, "https://github.com/dotnet/roslyn/issues/22495")> Public Async Function RenameDeconstructionForeachCollection(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> [|$$x|]) { foreach (var (y1, y2) in [|x|]) { } } void Deconstruct(out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "x", "change", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameDeconstructMethodInDeconstructionForeach(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document><![CDATA[ using System.Collections.Generic; class Deconstructable { void M(IEnumerable<Deconstructable> x) { foreach (var (y1, y2) in x) { } var (z1, z2) = this; [|Deconstruct|](out var t1, out var t2); } void [|$$Deconstruct|](out int i, out int j) { i = 0; j = 0; } } ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "Deconstruct", "Changed", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(540120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540120")> Public Async Function SimpleEditAndVerifyTagsPropagatedAndCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function Private Shared Async Function VerifyRenameOptionChangedSessionCommit(workspace As TestWorkspace, originalTextToRename As String, renameTextPrefix As String, Optional renameOverloads As Boolean = False, Optional renameInStrings As Boolean = False, Optional renameInComments As Boolean = False, Optional renameFile As Boolean = False, Optional fileToRename As DocumentId = Nothing) As Task Dim optionSet = workspace.Options optionSet = optionSet.WithChangedOption(RenameOptions.RenameOverloads, renameOverloads) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInStrings, renameInStrings) optionSet = optionSet.WithChangedOption(RenameOptions.RenameInComments, renameInComments) optionSet = optionSet.WithChangedOption(RenameOptions.RenameFile, renameFile) workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)) Dim session = StartSession(workspace) ' Type a bit in the file Dim renameDocument As TestHostDocument = workspace.DocumentWithCursor renameDocument.GetTextBuffer().Insert(renameDocument.CursorPosition.Value, renameTextPrefix) Dim replacementText = renameTextPrefix + originalTextToRename Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, replacementText) session.Commit() Await VerifyTagsAreCorrect(workspace, replacementText) If renameFile Then If fileToRename Is Nothing Then VerifyFileName(workspace, replacementText) Else VerifyFileName(workspace.CurrentSolution.GetDocument(fileToRename), replacementText) End If End If End Function <WpfTheory(Skip:="https://github.com/dotnet/roslyn/issues/13186")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Program { public void [|$$goo|]() { [|goo|](); } public void [|goo|]&lt;T&gt;() { [|goo|]&lt;T&gt;(); } public void [|goo|](int i) { [|goo|](i); } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700921")> Public Async Function RenameOverloadsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Imports System.Collections.Generic Imports System.Linq Imports System Public Class Program Sub Main(args As String()) End Sub Public Sub [|$$goo|]() [|goo|]() End Sub Public Sub [|goo|](of T)() [|goo|](of T)() End Sub Public Sub [|goo|](s As String) [|goo|](s) End Sub Public Shared Sub [|goo|](d As Double) [|goo|](d) End Sub End Class </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(960955, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960955")> Public Async Function RenameParameterShouldNotAffectCommentsInOtherDocuments(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Program Sub Main([|$$args|] As String()) End Sub End Class </Document> <Document> ' args </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "args", "bar", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "Test1.vb")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesDoesNotCrash(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) ' https://github.com/dotnet/roslyn/issues/36075 ' VerifyFileRename(workspace, "ABC") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesHandlesBothProjects(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class [|$$C|] { } // [|C|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|C|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPrivateAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { private void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // F ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(1040098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1040098")> Public Async Function RenameInLinkedFilesWithPublicAccessibility(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[ public partial class C { public void [|$$F|](){} } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> <Document FilePath="C2.cs"><![CDATA[ public partial class C { } // [|F|] ]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj3"> <ProjectReference>Proj2</ProjectReference> <Document FilePath="C3.cs"><![CDATA[ // [|F|] ]]></Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "F", "AB", renameInComments:=True) Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3623, "https://github.com/dotnet/roslyn/issues/3623")> Public Async Function RenameTypeInLinkedFiles(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"><![CDATA[ public class [|$$C|] { } ]]></Document> </Project> <Project Language="C#" CommonReferences="true" AssemblyName="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "AB") Assert.NotNull(workspace.Documents.FirstOrDefault(Function(document) document.Name = "C.cs")) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsCSharp(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.goo(System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "goo"; var b = $"{1}goo{2}"; } public void [|goo|](int i) { [|goo|](i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|]")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:Program.[|goo|](System.Int32)")] class Program { /// <[|goo|]> [|goo|]! </[|goo|]> public void [|$$goo|]() { // [|goo|] GOO /* [|goo|] */ [|goo|](); var a = "[|goo|]"; var b = $"{1}[|goo|]{2}"; } public void goo(int i) { goo(i); } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(700923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700923"), WorkItem(700925, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/700925"), WorkItem(1486, "https://github.com/dotnet/roslyn/issues/1486")> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameInCommentsAndStringsVisualBasic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.goo(System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "goo" Dim b = $"{1}goo{2}" End Sub Public Sub [|goo|](i As Integer) [|goo|](i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameOverloads:=True, renameInComments:=True) VerifyFileName(workspace, "Test1") End Using Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> <![CDATA[ <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|]")> <Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope:="member", Target:="~M:Program.[|goo|](System.Int32)")> Class Program ''' <[|goo|]> [|goo|]! </[|goo|]> Public Sub [|$$goo|]() ' [|goo|] GOO ' [|goo|] [|goo|]() Dim a = "[|goo|]" Dim b = $"{1}[|goo|]{2}" End Sub Public Sub goo(i As Integer) goo(i) End Sub End Class ]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "goo", "bar", renameInComments:=True, renameInStrings:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub SimpleEditAndCancel(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim initialTextSnapshot = textBuffer.CurrentSnapshot textBuffer.Insert(caretPosition, "Bar") session.Cancel() ' Assert the file is what it started as Assert.Equal(initialTextSnapshot.GetText(), textBuffer.CurrentSnapshot.GetText()) ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <WorkItem(539513, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539513")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function CanRenameTypeNamedDynamic(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$dynamic|] { void M() { [|dynamic|] d; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "goo") session.Commit() Await VerifyTagsAreCorrect(workspace, "goodynamic") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub ReadOnlyRegionsCreated(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class $$C { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Dim cursorPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Assert.False(buffer.IsReadOnly(cursorPosition)) Assert.False(buffer.IsReadOnly(cursorPosition + 1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) ' Make sure we can't type at the start or end Assert.True(buffer.IsReadOnly(0)) Assert.True(buffer.IsReadOnly(buffer.CurrentSnapshot.Length)) session.Cancel() ' Assert the file name didn't change VerifyFileName(workspace, "Test1.cs") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(543018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543018")> Public Sub ReadOnlyRegionsCreatedWhichHandleBeginningOfFileEdgeCase(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document>$$C c; class C { }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim buffer = workspace.Documents.Single().GetTextBuffer() ' Typing at the beginning and end of our span should work Assert.False(buffer.IsReadOnly(0)) Assert.False(buffer.IsReadOnly(1)) ' Replacing our span should work Assert.False(buffer.IsReadOnly(New Span(workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value, length:=1))) session.Cancel() VerifyFileName(workspace, "Test1.cs") End Using End Sub <Theory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub RenameWithInheritenceCascadingWithClass(host As RenameTestHost) Using result = RenameEngineResult.Create(_outputHelper, <Workspace> <Project Language="C#" CommonReferences="true"> <Document> abstract class AAAA { public abstract void [|Goo|](); } class BBBB : AAAA { public override void [|Goo|]() { } } class DDDD : BBBB { public override void [|Goo|]() { } } class CCCC : AAAA { public override void [|$$Goo|]() { } } </Document> </Project> </Workspace>, host:=host, renameTo:="GooBar") End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530467")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyNoRenameTrackingAfterInlineRenameTyping2(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(579210, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579210")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(530765, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530765")> Public Async Function VerifyNoRenameTrackingAfterInlineRenameCancel(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarGoo") session.Cancel() Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyRenameTrackingWorksAfterInlineRenameCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() Dim document = workspace.Documents.Single() Dim renameTrackingTagger = CreateRenameTrackingTagger(workspace, document) textBuffer.Insert(caretPosition, "Bar") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "BarTest1") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarTest1") Await VerifyNoRenameTrackingTags(renameTrackingTagger, workspace, document) VerifyFileName(workspace, "BarTest1") textBuffer.Insert(caretPosition, "Baz") Await VerifyRenameTrackingTags(renameTrackingTagger, workspace, document, expectedTagCount:=1) End Using End Function <WpfTheory, WorkItem(978099, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/978099")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) ' Preview should not return null Dim previewService = DirectCast(workspace.Services.GetRequiredService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = False Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) Assert.Equal(String.Format(EditorFeaturesResources.Preview_Changes_0, EditorFeaturesResources.Rename), previewService.Title) Assert.Equal(String.Format(EditorFeaturesResources.Rename_0_to_1_colon, "Goo", "BarGoo"), previewService.Description) Assert.Equal("Goo", previewService.TopLevelName) Assert.Equal(Glyph.ClassInternal, previewService.TopLevelGlyph) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyPreviewChangesCancellation(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { [|Goo|] f = new [|Goo|](); } } </Document> </Project> </Workspace>, host) Dim previewService = DirectCast(workspace.Services.GetService(Of IPreviewDialogService)(), MockPreviewDialogService) previewService.ReturnsNull = True Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "BarGoo") Assert.True(previewService.Called) ' Session should still be up; type some more caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value textBuffer.Insert(caretPosition, "Cat") previewService.ReturnsNull = False previewService.Called = False session.Commit(previewChanges:=True) Await VerifyTagsAreCorrect(workspace, "CatBarGoo") Assert.True(previewService.Called) VerifyFileName(workspace, "Test1.cs") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_MethodWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Sub [|M$$|]() End Sub Sub Test() #If Proj1 Then [|M|]() #End If #If Proj2 Then [|M|]() #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "o") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mo") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Mow") session.Commit() Await VerifyTagsAreCorrect(workspace, "Mow") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function VerifyLinkedFiles_FieldWithReferences(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBProj" PreprocessorSymbols="Proj1=True"> <Document FilePath="C.vb"> Class C Dim [|m$$|] As Integer Sub Test() #If Proj1 Then Dim x = [|m|] #End If #If Proj2 Then Dim x = [|m|] #End If End Sub End Class </Document> </Project> <Project Language="Visual Basic" CommonReferences="true" PreprocessorSymbols="Proj2=True"> <Document IsLinkFile="true" LinkAssemblyName="VBProj" LinkFilePath="C.vb"/> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "ma") textBuffer.Insert(caretPosition + 1, "w") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "maw") session.Commit() Await VerifyTagsAreCorrect(workspace, "maw") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <Trait(Traits.Feature, Traits.Features.CodeActionsIntroduceVariable)> <WorkItem(554, "https://github.com/dotnet/roslyn/issues/554")> Public Async Function CodeActionCannotCommitDuringInlineRename(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj"> <Document FilePath="C.cs"> class C { void M() { var z = {|introducelocal:5 + 5|}; var q = [|x$$|]; } int [|x|]; }</Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "yz") Await WaitForRename(workspace) ' Invoke a CodeAction Dim introduceVariableRefactoringProvider = New IntroduceVariableCodeRefactoringProvider() Dim actions = New List(Of CodeAction) Dim context = New CodeRefactoringContext( workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), workspace.Documents.Single().AnnotatedSpans()("introducelocal").Single(), Sub(a) actions.Add(a), CancellationToken.None) workspace.Documents.Single().AnnotatedSpans.Clear() introduceVariableRefactoringProvider.ComputeRefactoringsAsync(context).Wait() Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService) Dim actualSeverity As NotificationSeverity = Nothing Dim notificationService = DirectCast(workspace.Services.GetService(Of INotificationService)(), INotificationServiceCallback) notificationService.NotificationCallback = Sub(message, title, severity) actualSeverity = severity editHandler.Apply( workspace, workspace.CurrentSolution.GetDocument(workspace.Documents.Single().Id), Await actions.First().NestedCodeActions.First().GetOperationsAsync(CancellationToken.None), "unused", New ProgressTracker(), CancellationToken.None) ' CodeAction should be rejected Assert.Equal(NotificationSeverity.Error, actualSeverity) Assert.Equal(" class C { void M() { var z = 5 + 5; var q = xyz; } int xyz; }", textBuffer.CurrentSnapshot.GetText()) ' Rename should still be active Await VerifyTagsAreCorrect(workspace, "xyz") textBuffer.Insert(caretPosition + 2, "q") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "xyzq") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof([|M|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_NoOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M$$|]() { nameof(M).ToString(); } void M(int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromReference_WithOverloads(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|M|]() { nameof([|M$$|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.First(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.First().GetTextBuffer() textBuffer.Insert(caretPosition, "a") Await WaitForRename(workspace) Await VerifyTagsAreCorrect(workspace, "Ma") session.Commit() Await VerifyTagsAreCorrect(workspace, "Ma") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameMethodWithNameof_FromDefinition_WithOverloads_WithRenameOverloadsOption(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class C { void [|$$M|]() { nameof([|M|]).ToString(); } void [|M|](int x) { } } </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "M", "Sa", renameOverloads:=True) VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(3316, "https://github.com/dotnet/roslyn/issues/3316")> Public Async Function InvalidInvocationExpression(host As RenameTestHost) As Task ' Everything on the last line of main is parsed as a single invocation expression ' with CType(...) as the receiver and everything else as arguments. ' Rename doesn't expect to see CType as the receiver of an invocation. Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Module Module1 Sub Main() Dim [|$$p|] As IEnumerable(Of Integer) = {1, 2, 3} Dim linked = Enumerable.Aggregate(Of Global.&lt;anonymous type:head As Global.System.Int32, tail As Global.System.Object&gt;)( CType([|p|], IEnumerable(Of Integer)), Nothing, Function(total, curr) Nothing) End Sub End Module </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "q") session.Commit() Await VerifyTagsAreCorrect(workspace, "qp") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(2445, "https://github.com/dotnet/roslyn/issues/2445")> Public Async Function InvalidExpansionTarget(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> int x; x = 2; void [|$$M|]() { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "x") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(9117, "https://github.com/dotnet/roslyn/issues/9117")> Public Async Function VerifyVBRenameCrashDoesNotRepro(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Public Class Class1 Public Property [|$$Field1|] As Integer End Class Public Class Class2 Public Shared Property DataSource As IEnumerable(Of Class1) Public ReadOnly Property Dict As IReadOnlyDictionary(Of Integer, IEnumerable(Of Class1)) = ( From data In DataSource Group By data.Field1 Into Group1 = Group ).ToDictionary( Function(group) group.Field1, Function(group) group.Group1) End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "x") session.Commit() Await VerifyTagsAreCorrect(workspace, "xield1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(14554, "https://github.com/dotnet/roslyn/issues/14554")> Public Sub VerifyVBRenameDoesNotCrashOnAsNewClause(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="Visual Basic" CommonReferences="true"> <Document> Class C Sub New(a As Action) End Sub Public ReadOnly Property Vm As C Public ReadOnly Property Crash As New C(Sub() Vm.Sav() End Sub) Public Function Sav$$() As Boolean Return False End Function Public Function Save() As Boolean Return False End Function End Class </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() ' Ensure the rename doesn't crash textBuffer.Insert(caretPosition, "e") session.Commit() End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedForPartialType(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Goo|] { void Blah() { } } </Document> <Document> partial class Goo { void BlahBlah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeWithMultipleLocations, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedForPartialTypeWithSingleLocation(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> partial class [|$$Test1|] { void Blah() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameAllowedWithMultipleTypesOnMatchingName(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { } } class Test2 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyNoFileRenameAllowedWithMultipleTypes(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Goo|] { void Blah() { } } class Test1 { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.TypeDoesNotMatchFileName, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyEnumKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> enum [|$$Test1|] { One, Two, Three } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyInterfaceKindSupportsFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface [|$$Test1|] { void Blah(); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.Allowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyUnsupportedFileRename(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> interface Test1 { void [|$$Blah|](); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenameNotAllowedForLinkedFiles(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" AssemblyName="CSProj" PreprocessorSymbols="Proj1"> <Document FilePath="C.cs"><![CDATA[public class [|$$C|] { } // [|C|]]]></Document> </Project> <Project Language="C#" CommonReferences="true" PreprocessorSymbols="Proj2"> <Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/> </Project> </Workspace>, host) ' Disable document changes to make sure file rename is not supported. ' Linked workspace files will report that applying changes to document ' info is not allowed; this is intended to mimic that behavior ' and make sure inline rename works as intended. workspace.CanApplyChangeDocument = False Dim session = StartSession(workspace) Assert.Equal(InlineRenameFileRenameInfo.NotAllowed, session.FileRenameInfo) End Using End Sub <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Sub VerifyFileRenamesCorrectlyWhenCaseChanges(host As RenameTestHost) Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Delete(New Span(caretPosition, 1)) textBuffer.Insert(caretPosition, "t") session.Commit() VerifyFileName(workspace, "test1") End Using End Sub <WpfTheory, WorkItem(36063, "https://github.com/dotnet/roslyn/issues/36063")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function EditBackToOriginalNameThenCommit(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class [|$$Test1|] { void Blah() { [|Test1|] f = new [|Test1|](); } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") textBuffer.Delete(New Span(caretPosition, "Bar".Length)) Dim committed = session.GetTestAccessor().CommitWorker(previewChanges:=False) Assert.False(committed) Await VerifyTagsAreCorrect(workspace, "Test1") End Using End Function <WpfTheory, WorkItem(44576, "https://github.com/dotnet/roslyn/issues/44576")> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameFromOtherFile(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> class Test1 { void Blah() { [|$$Test2|] t2 = new [|Test2|](); } } </Document> <Document Name="Test2.cs"> class Test2 { } </Document> </Project> </Workspace>, host) Dim docToRename = workspace.Documents.First(Function(doc) doc.Name = "Test2.cs") Await VerifyRenameOptionChangedSessionCommit(workspace, originalTextToRename:="Test2", renameTextPrefix:="Test2Changed", renameFile:=True, fileToRename:=docToRename.Id) End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> <WorkItem(44288, "https://github.com/dotnet/roslyn/issues/44288")> Public Async Function RenameConstructorReferencedInGlobalSuppression(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true"> <Document> <![CDATA[ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Category", "RuleId", Scope = "member", Target = "~M:[|C|].#ctor")] class [|C|] { public [|$$C|]() { } }]]> </Document> </Project> </Workspace>, host) Await VerifyRenameOptionChangedSessionCommit(workspace, "C", "D") VerifyFileName(workspace, "Test1") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithNoBody1(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a); class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordWithBody(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g; } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameRecordConstructorCalled(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="9.0"> <Document> record [|$$Goo|](int a) { } class C { [|Goo|] g = new [|Goo|](1); } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameExtendedProperty(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class C { void M() { _ = this is { Other.[|Goo|]: not null, Other.Other.[|Goo|]: not null, [|Goo|]: null } ; } public C [|$$Goo|] { get; set; } public C Other { get; set; } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) ' Type a bit in the file Dim caretPosition = workspace.Documents.Single(Function(d) d.CursorPosition.HasValue).CursorPosition.Value Dim textBuffer = workspace.Documents.Single().GetTextBuffer() textBuffer.Insert(caretPosition, "Bar") session.Commit() Await VerifyTagsAreCorrect(workspace, "BarGoo") End Using End Function <WpfTheory> <CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)> Public Async Function RenameInComment(host As RenameTestHost) As Task Using workspace = CreateWorkspaceWithWaiter( <Workspace> <Project Language="C#" CommonReferences="true" LanguageVersion="preview"> <Document> class [|$$MyClass|] { /// <summary> /// Initializes <see cref="MyClass"/>; /// </summary> MyClass() { } } </Document> </Project> </Workspace>, host) Dim session = StartSession(workspace) session.ApplyReplacementText("Example", True) session.RefreshRenameSessionWithOptionsChanged(RenameOptions.RenameInComments, True) session.Commit() Await VerifyTagsAreCorrect(workspace, "Example") End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/ExpressionEvaluator/CSharp/Source/ExpressionCompiler/CSharpLocalAndMethod.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.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CSharpLocalAndMethod : LocalAndMethod { private readonly MethodSymbol _method; public CSharpLocalAndMethod(string name, string displayName, MethodSymbol method, DkmClrCompilationResultFlags flags) : base(name, displayName, method.Name, flags) { Debug.Assert(method is EEMethodSymbol); // Expected but not required. _method = method; } /// <remarks> /// The custom type info payload depends on the return type, which is not available when /// <see cref="CSharpLocalAndMethod"/> is created. /// </remarks> public override Guid GetCustomTypeInfo(out ReadOnlyCollection<byte>? payload) { payload = _method.GetCustomTypeInfoPayload(); return (payload == null) ? default : CustomTypeInfo.PayloadTypeId; } } }
// Licensed to the .NET Foundation under one or more 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.ObjectModel; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed class CSharpLocalAndMethod : LocalAndMethod { private readonly MethodSymbol _method; public CSharpLocalAndMethod(string name, string displayName, MethodSymbol method, DkmClrCompilationResultFlags flags) : base(name, displayName, method.Name, flags) { Debug.Assert(method is EEMethodSymbol); // Expected but not required. _method = method; } /// <remarks> /// The custom type info payload depends on the return type, which is not available when /// <see cref="CSharpLocalAndMethod"/> is created. /// </remarks> public override Guid GetCustomTypeInfo(out ReadOnlyCollection<byte>? payload) { payload = _method.GetCustomTypeInfoPayload(); return (payload == null) ? default : CustomTypeInfo.PayloadTypeId; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Test/Semantic/Semantics/RecordTests.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.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion() { var src1 = @" class Point(int x, int y); "; var src2 = @" record Point { } "; var src3 = @" record Point(int x, int y); "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS0116: A namespace cannot directly contain members such as fields or methods // record Point { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Point").WithLocation(2, 8), // (2,8): error CS0548: '<invalid-global-code>.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("<invalid-global-code>.Point").WithLocation(2, 8) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS8805: Program using top-level statements must be an executable. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "record Point(int x, int y);").WithLocation(2, 1), // (2,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "record Point(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 1), // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS8112: Local function 'Point(int, int)' must declare a body because it is not marked 'static extern'. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Point").WithArguments("Point(int, int)").WithLocation(2, 8), // (2,8): warning CS8321: The local function 'Point' is declared but never used // record Point(int x, int y); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Point").WithArguments("Point").WithLocation(2, 8) ); comp = CreateCompilation(src1, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); var point = comp.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsReferenceType); Assert.False(point.IsValueType); Assert.Equal(TypeKind.Class, point.TypeKind); Assert.Equal(SpecialType.System_Object, point.BaseTypeNoUseSiteDiagnostics.SpecialType); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion_Nested() { var src1 = @" class C { class Point(int x, int y); } "; var src2 = @" class D { record Point { } } "; var src3 = @" class E { record Point(int x, int y); } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0548: 'D.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("D.Point").WithLocation(4, 12) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0501: 'E.Point(int, int)' must declare a body because it is not marked abstract, extern, or partial // record Point(int x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "Point").WithArguments("E.Point(int, int)").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordClassLanguageVersion() { var src = @" record class Point(int x, int y); "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "record").WithLocation(2, 1), // (2,19): error CS1514: { expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS1513: } expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 19), // (2,19): error CS8803: Top-level statements must precede namespace and type declarations. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS8805: Program using top-level statements must be an executable. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 19), // (2,20): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'x' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 20), // (2,27): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 27), // (2,27): error CS0165: Use of unassigned local variable 'y' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 27) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "class").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [CombinatorialData] [Theory, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers(bool useCompilationReference) { var lib_src = @" public record RecordA(RecordB B); public record RecordB(int C); "; var lib_comp = CreateCompilation(lib_src); var src = @" class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src, references: new[] { AsReference(lib_comp, useCompilationReference) }); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_SingleCompilation() { var src = @" public record RecordA(RecordB B); public record RecordB(int C); class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); Assert.Equal("System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor() { var src = @" record R(R x); #nullable enable record R2(R2? x) { } record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2(R2? x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8), // (7,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R3").WithLocation(7, 8) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R original)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_Generic() { var src = @" record R<T>(R<T> x); #nullable enable record R2<T>(R2<T?> x) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R<T>(R<T> x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2<T>(R2<T?> x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithExplicitCopyCtor() { var src = @" record R(R x) { public R(R x) => throw null; } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,12): error CS0111: Type 'R' already defines a member called 'R' with the same parameter types // public R(R x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R").WithArguments("R", "R").WithLocation(4, 12) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R x)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithBase() { var src = @" record Base; record R(R x) : Base; // 1 record Derived(Derived y) : R(y) // 2 { public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 } record Derived2(Derived2 y) : R(y); // 6, 7, 8 record R2(R2 x) : Base { public R2(R2 x) => throw null; // 9, 10 } record R3(R3 x) : Base { public R3(R3 x) : base(x) => throw null; // 11 } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x) : Base; // 1 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(4, 8), // (6,30): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived(Derived y) : R(y) // 2 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(6, 30), // (8,12): error CS0111: Type 'Derived' already defines a member called 'Derived' with the same parameter types // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Derived").WithArguments("Derived", "Derived").WithLocation(8, 12), // (8,33): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_AmbigCall, "base").WithArguments("R.R(R)", "R.R(R)").WithLocation(8, 33), // (8,33): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(8, 33), // (11,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "Derived2").WithLocation(11, 8), // (11,8): error CS8867: No accessible copy constructor found in base type 'R'. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "Derived2").WithArguments("R").WithLocation(11, 8), // (11,32): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(11, 32), // (15,12): error CS0111: Type 'R2' already defines a member called 'R2' with the same parameter types // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R2").WithArguments("R2", "R2").WithLocation(15, 12), // (15,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "R2").WithLocation(15, 12), // (20,12): error CS0111: Type 'R3' already defines a member called 'R3' with the same parameter types // public R3(R3 x) : base(x) => throw null; // 11 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R3").WithArguments("R3", "R3").WithLocation(20, 12) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithPropertyInitializer() { var src = @" record R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R X) Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record R(int I) { public int I { get; init; } = M(out int i) ? i : 0; static bool M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord() { string source = @" public record A(int i,) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 23) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "? A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32 i, ?)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTrivia() { string source = @" public record A(int i, // A // B , /* C */ ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 23), // (4,15): error CS1031: Type expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 15), // (4,15): error CS1001: Identifier expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 15), // (4,15): error CS0102: The type 'A' already contains a definition for '' // , /* C */ ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 15) ); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[2].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompleteConstructor() { string source = @" public class C { C(int i, ) { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,14): error CS1031: Type expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 14), // (4,14): error CS1001: Identifier expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14) ); var ctor = comp.GetMember<NamedTypeSymbol>("C").Constructors.Single(); Assert.Equal("C..ctor(System.Int32 i, ?)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithType() { string source = @" public record A(int i, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS1001: Identifier expected // public record A(int i, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.Equal("A..ctor(System.Int32 i, System.Int32)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes() { string source = @" public record A(int, string ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,29): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 29), // (2,29): error CS0102: The type 'A' already contains a definition for '' // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 29) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.String A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.String)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_SameType() { string source = @" public record A(int, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,26): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 26), // (2,26): error CS0102: The type 'A' already contains a definition for '' // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 26) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.Int32)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_WithTrivia() { string source = @" public record A(int // A // B , int /* C */) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 20), // (4,18): error CS1001: Identifier expected // , int /* C */) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 18), // (4,18): error CS0102: The type 'A' already contains a definition for '' // , int /* C */) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 18) ); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.IsType<ParameterSyntax>(ctor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46083, "https://github.com/dotnet/roslyn/issues/46083")] public void IncompletePositionalRecord_SingleParameter() { string source = @" record A(x) "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // record A(x) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(2, 10), // (2,11): error CS1001: Identifier expected // record A(x) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 11), // (2,12): error CS1514: { expected // record A(x) Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 12), // (2,12): error CS1513: } expected // record A(x) Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 12) ); } [Fact] public void TestWithInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public record C(int i) { public static void M() { Expression<Func<C, C>> expr = c => c with { i = 5 }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,44): error CS8849: An expression tree may not contain a with-expression. // Expression<Func<C, C>> expr = c => c with { i = 5 }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsWithExpression, "c with { i = 5 }").WithLocation(8, 44) ); } [Fact] public void PartialRecord_MixedWithClass() { var src = @" partial record C(int X, int Y) { } partial class C { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,15): error CS0261: Partial declarations of 'C' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C").WithArguments("C").WithLocation(5, 15) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts_RecordClass() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record class C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record C(int X) { public void M(int i) { } } public partial record C { public void M(string s) { } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }); var expectedMemberNames = new string[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record Nested(T T); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordProperties_01() { var src = @" using System; record C(int X, int Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: call ""object..ctor()"" IL_001c: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_02() { var src = @" using System; record C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 0 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 3 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void RecordProperties_05() { var src = @" record C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0100: The parameter name 'X' is a duplicate // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 21), // (2,21): error CS0102: The type 'C' already contains a definition for 'X' // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 21) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_05_RecordClass() { var src = @" record class C(int X, int X) { }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,27): error CS0100: The parameter name 'X' is a duplicate // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 27), // (2,27): error CS0102: The type 'C' already contains a definition for 'X' // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 27) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,14): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 14), // (2,21): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 21)); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", "System.Int32 C.X { get; init; }", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Y.init", "System.Int32 C.Y { get; init; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record C1(object P, object get_P); record C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,18): error CS0102: The type 'C1' already contains a definition for 'get_P' // record C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 18), // (3,32): error CS0102: The type 'C2' already contains a definition for 'get_P' // record C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 32) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @"record C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,15): error CS0721: 'C2': static types cannot be used as parameters // unsafe record C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 15), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,22): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 22), // (4,33): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 33), // (4,47): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 47) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } record Base(object O); record C2(object O4) : Base(O4) // we didn't complain because the parameter is read { public object O4 { get; init; } } record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 { public object O5 { get; init; } } record C4(object O6) : Base((System.Func<object, object>)(_ => O6)) { public object O6 { get; init; } } record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 { public object O7 { get; init; } } "); comp.VerifyDiagnostics( // (2,18): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 18), // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40), // (16,18): warning CS8907: Parameter 'O5' is unread. Did you forget to use it to initialize the property with that name? // record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O5").WithArguments("O5").WithLocation(16, 18), // (26,18): warning CS8907: Parameter 'O7' is unread. Did you forget to use it to initialize the property with that name? // record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O7").WithArguments("O7").WithLocation(26, 18) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40) ); } [Fact] public void EmptyRecord_01() { var src = @" record C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_01_RecordClass() { var src = @" record class C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True", parseOptions: TestOptions.Regular10); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_02() { var src = @" record C() { C(int x) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // C(int x) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C", isSuppressed: false).WithLocation(4, 5) ); } [Fact] public void EmptyRecord_03() { var src = @" record B { public B(int x) { System.Console.WriteLine(x); } } record C() : B(12) { C(int x) : this() {} } class Program { static void Main() { _ = new C(); } } "; var verifier = CompileAndVerify(src, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 12 IL_0003: call ""B..ctor(int)"" IL_0008: ret } "); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // [ : R::set_x] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record R() { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_CopyCtor() { var src = @" record R() { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void WithExpr1() { var src = @" record C(int X) { public static void Main() { var c = new C(0); _ = Main() with { }; _ = default with { }; _ = null with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = Main() with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "Main()").WithLocation(7, 13), // (8,13): error CS8716: There is no target type for the default literal. // _ = default with { }; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 13), // (9,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = null with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "null").WithLocation(9, 13) ); } [Fact] public void WithExpr2() { var src = @" using System; record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; Console.WriteLine(c1.X); Console.WriteLine(c2.X); } }"; CompileAndVerify(src, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void WithExpr3() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var root = comp.SyntaxTrees[0].GetRoot(); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { }') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr4() { var src = @" class B { public B Clone() => null; } record C(int X) : B { public static void Main() { var c = new C(0); c = c with { }; } public new C Clone() => null; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr6() { var src = @" record B { public int X { get; init; } } record C : B { public static void Main() { var c = new C(); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr7() { var src = @" record B { public int X { get; } } record C : B { public new int X { get; init; } public static void Main() { var c = new C(); B b = c; b = b with { X = 0 }; var b2 = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,22): error CS0200: Property or indexer 'B.X' cannot be assigned to -- it is read only // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "X").WithArguments("B.X").WithLocation(14, 22) ); } [Fact] public void WithExpr8() { var src = @" record B { public int X { get; } } record C : B { public string Y { get; } public static void Main() { var c = new C(); B b = c; b = b with { }; b = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr9() { var src = @" record C(int X) { public string Clone() => null; public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS8859: Members named 'Clone' are disallowed in records. // public string Clone() => null; Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(4, 19) ); } [Fact] public void WithExpr11() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """"}; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = ""}; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExpr12() { var src = @" using System; record C(int X) { public static void Main() { var c = new C(0); Console.WriteLine(c.X); c = c with { X = 5 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 5").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""int C.X.get"" IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0016: dup IL_0017: ldc.i4.5 IL_0018: callvirt ""void C.X.init"" IL_001d: callvirt ""int C.X.get"" IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ret }"); } [Fact] public void WithExpr13() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [Fact] public void WithExpr14() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); c = c with { Y = 2 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1 5 2").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: dup IL_001a: call ""void System.Console.WriteLine(object)"" IL_001f: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0024: dup IL_0025: ldc.i4.2 IL_0026: callvirt ""void C.Y.init"" IL_002b: call ""void System.Console.WriteLine(object)"" IL_0030: ret }"); } [Fact] public void WithExpr15() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { = 5 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS1525: Invalid expression term '=' // c = c with { = 5 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(8, 22) ); } [Fact] public void WithExpr16() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { X = }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS1525: Invalid expression term '}' // c = c with { X = }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr17() { var src = @" record B { public int X { get; } private B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr18() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The receiver type 'B' does not have an accessible parameterless instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr19() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr20() { var src = @" using System; record C { public event Action X; public static void Main() { var c = new C(); c = c with { X = null }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.X' is never used // public event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(5, 25) ); } [Fact] public void WithExpr21() { var src = @" record B { public class X { } } class C { public static void Main() { var b = new B(); b = b with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0572: 'X': cannot reference a type through an expression; try 'B.X' instead // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_BadTypeReference, "X").WithArguments("X", "B.X").WithLocation(11, 22), // (11,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(11, 22) ); } [Fact] public void WithExpr22() { var src = @" record B { public int X = 0; } class C { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr23() { var src = @" class B { public int X = 0; public B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { Y = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8858: The receiver type 'B' is not a valid record type. // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13), // (12,22): error CS0117: 'B' does not contain a definition for 'Y' // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Y").WithArguments("B", "Y").WithLocation(12, 22) ); } [Fact] public void WithExpr24_Dynamic() { var src = @" record C(int X) { public static void Main() { dynamic c = new C(1); var x = c with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,17): error CS8858: The receiver type 'dynamic' is not a valid record type. // var x = c with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("dynamic").WithLocation(7, 17) ); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr25_TypeParameterWithRecordConstraint() { var src = @" record R(int X); class C { public static T M<T>(T t) where T : R { return t with { X = 2 }; } static void Main() { System.Console.Write(M(new R(-1)).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "2").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.init"" IL_001c: ret } "); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr26_TypeParameterWithRecordAndInterfaceConstraint() { var src = @" record R { public int X { get; set; } } interface I { int Property { get; set; } } record T : R, I { public int Property { get; set; } } class C { public static T M<T>(T t) where T : R, I { return t with { X = 2, Property = 3 }; } static void Main() { System.Console.WriteLine(M(new T()).X); System.Console.WriteLine(M(new T()).Property); } }"; var verifier = CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, verify: Verification.Passes, expectedOutput: @"2 3").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 41 (0x29) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.set"" IL_001c: dup IL_001d: box ""T"" IL_0022: ldc.i4.3 IL_0023: callvirt ""void I.Property.set"" IL_0028: ret } "); } [Fact] public void WithExpr27_InExceptionFilter() { var src = @" var r = new R(1); try { throw new System.Exception(); } catch (System.Exception) when ((r = r with { X = 2 }).X == 2) { System.Console.Write(""RAN ""); System.Console.Write(r.X); } record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 2", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr28_WithAwait() { var src = @" var r = new R(1); r = r with { X = await System.Threading.Tasks.Task.FromResult(42) }; System.Console.Write(r.X); record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Last().Left; Assert.Equal("X", x.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal("System.Int32 R.X { get; init; }", symbol.ToTestDisplayString()); } [Fact, WorkItem(46465, "https://github.com/dotnet/roslyn/issues/46465")] public void WithExpr29_DisallowedAsExpressionStatement() { var src = @" record R(int X) { void M() { var r = new R(1); r with { X = 2 }; } } "; // Note: we didn't parse the `with` as a `with` expression, but as a broken local declaration // Tracked by https://github.com/dotnet/roslyn/issues/46465 var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,9): error CS0118: 'r' is a variable but is used like a type // r with { X = 2 }; Diagnostic(ErrorCode.ERR_BadSKknown, "r").WithArguments("r", "variable", "type").WithLocation(7, 9), // (7,11): warning CS0168: The variable 'with' is declared but never used // r with { X = 2 }; Diagnostic(ErrorCode.WRN_UnreferencedVar, "with").WithArguments("with").WithLocation(7, 11), // (7,16): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(7, 16), // (7,18): error CS8852: Init-only property or indexer 'R.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // r with { X = 2 }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "X").WithArguments("R.X").WithLocation(7, 18), // (7,24): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 24) ); } [Fact] public void WithExpr30_TypeParameterNoConstraint() { var src = @" class C { public static void M<T>(T t) { _ = t with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr31_TypeParameterWithInterfaceConstraint() { var src = @" interface I { int Property { get; set; } } class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(8, 13), // (8,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(8, 22) ); } [Fact] public void WithExpr32_TypeParameterWithInterfaceConstraint() { var ilSource = @" .class interface public auto ansi abstract I { // Methods .method public hidebysig specialname newslot abstract virtual instance class I '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { } // end of method I::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot abstract virtual instance int32 get_Property () cil managed { } // end of method I::get_Property .method public hidebysig specialname newslot abstract virtual instance void set_Property ( int32 'value' ) cil managed { } // end of method I::set_Property // Properties .property instance int32 Property() { .get instance int32 I::get_Property() .set instance void I::set_Property(int32) } } // end of class I "; var src = @" class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr33_TypeParameterWithStructureConstraint() { var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance valuetype S '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { // Method begins at RVA 0x2150 // Code size 2 (0x2) .maxstack 1 .locals init ( [0] valuetype S ) IL_0000: ldnull IL_0001: throw } // end of method S::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname instance int32 get_Property () cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::get_Property .method public hidebysig specialname instance void set_Property ( int32 'value' ) cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::set_Property // Properties .property instance int32 Property() { .get instance int32 S::get_Property() .set instance void S::set_Property(int32) } } // end of class S "; var src = @" abstract class Base<T> { public abstract void M<U>(U t) where U : T; } class C : Base<S> { public override void M<U>(U t) { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "t with { X = 2, Property = 3 }").WithArguments("with on structs", "10.0").WithLocation(11, 13), // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreDefined() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreNotDefined() { var src = @" public sealed record C { public object Data; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public sealed record C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord() { var src = @" class record { } class C { record M(record r) => r; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,7): error CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7), // (6,24): error CS1514: { expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_LbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1513: } expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(6, 24), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Struct() { var src = @" struct record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // struct record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Interface() { var src = @" interface record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,11): warning CS8860: Types and aliases should not be named 'record'. // interface record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 11) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Enum() { var src = @" enum record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,6): warning CS8860: Types and aliases should not be named 'record'. // enum record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 6) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate() { var src = @" delegate void record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // delegate void record(); Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate_Escaped() { var src = @" delegate void @record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias() { var src = @" using record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using record = System.Console;").WithLocation(2, 1), // (2,7): warning CS8860: Types and aliases should not be named 'record'. // using record = System.Console; Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias_Escaped() { var src = @" using @record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using @record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using @record = System.Console;").WithLocation(2, 1) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter() { var src = @" class C<record> { } // 1 class C2 { class Nested<record> { } // 2 } class C3 { void Method<record>() { } // 3 void Method2() { void local<record>() // 4 { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,9): warning CS8860: Types and aliases should not be named 'record'. // class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 9), // (5,18): warning CS8860: Types and aliases should not be named 'record'. // class Nested<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 18), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // void Method<record>() { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (13,20): warning CS8860: Types and aliases should not be named 'record'. // void local<record>() // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(13, 20) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped() { var src = @" class C<@record> { } class C2 { class Nested<@record> { } } class C3 { void Method<@record>() { } void Method2() { void local<@record>() { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped_Partial() { var src = @" partial class C<@record> { } partial class C<record> { } // 1 partial class D<record> { } // 2 partial class D<@record> { } partial class D<record> { } // 3 partial class D<record> { } // 4 partial class E<@record> { } partial class E<@record> { } partial class C2 { partial class Nested<record> { } // 5 partial class Nested<@record> { } } partial class C3 { partial void Method<@record>(); partial void Method<record>() { } // 6 partial void Method2<@record>() { } partial void Method2<record>(); // 7 partial void Method3<record>(); // 8 partial void Method3<@record>() { } partial void Method4<record>() { } // 9 partial void Method4<@record>(); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,17): warning CS8860: Types and aliases should not be named 'record'. // partial class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 17), // (5,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 17), // (8,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(8, 17), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (16,26): warning CS8860: Types and aliases should not be named 'record'. // partial class Nested<record> { } // 5 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(16, 26), // (22,25): warning CS8860: Types and aliases should not be named 'record'. // partial void Method<record>() { } // 6 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(22, 25), // (25,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method2<record>(); // 7 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(25, 26), // (27,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method3<record>(); // 8 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(27, 26), // (30,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method4<record>() { } // 9 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(30, 26) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Record() { var src = @" record record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // record record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TwoParts() { var src = @" partial class record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15), // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Escaped() { var src = @" class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial() { var src = @" partial class @record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial_ReversedOrder() { var src = @" partial class record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_BothEscapedPartial() { var src = @" partial class @record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeNamedRecord_EscapedReturnType() { var src = @" class record { } class C { @record M(record r) { System.Console.Write(""RAN""); return r; } public static void Main() { var c = new C(); _ = c.M(new record()); } }"; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (2,7): warning CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record C1(string Clone); // 1 record C2 { string Clone; // 2 } record C3 { string Clone { get; set; } // 3 } record C4 { data string Clone; // 4 not yet supported } record C5 { void Clone() { } // 5 void Clone(int i) { } // 6 } record C6 { class Clone { } // 7 } record C7 { delegate void Clone(); // 8 } record C8 { event System.Action Clone; // 9 } record Clone { Clone(int i) => throw null; } record C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,18): error CS8859: Members named 'Clone' are disallowed in records. // record C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 18), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS1519: Invalid token 'string' in class, record, struct, or interface member declaration // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "string").WithArguments("string").WithLocation(13, 10), // (13,17): error CS8859: Members named 'Clone' are disallowed in records. // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 17), // (13,17): warning CS0169: The field 'C4.Clone' is never used // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C4.Clone").WithLocation(13, 17), // (17,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(17, 10), // (18,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 10), // (22,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 11), // (26,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 19), // (30,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 9 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(30, 25), // (30,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 9 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(30, 25) ); } [Fact] public void Clone_LoadedFromMetadata() { // IL for ' public record Base(int i);' with a 'void Clone()' method added var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .field private initonly int32 '<i>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname newslot virtual instance class Base '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void Base::.ctor(class Base) IL_0006: ret } .method family hidebysig specialname newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldtoken Base IL_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000a: ret } .method public hidebysig specialname rtspecialname instance void .ctor ( int32 i ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: ret } .method public hidebysig specialname instance int32 get_i () cil managed { IL_0000: ldarg.0 IL_0001: ldfld int32 Base::'<i>k__BackingField' IL_0006: ret } .method public hidebysig specialname instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_i ( int32 'value' ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ret } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::get_Default() IL_0005: ldarg.0 IL_0006: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000b: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::GetHashCode(!0) IL_0010: ldc.i4 -1521134295 IL_0015: mul IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::GetHashCode(!0) IL_0026: add IL_0027: ret } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst Base IL_0007: callvirt instance bool Base::Equals(class Base) IL_000c: ret } .method public newslot virtual instance bool Equals ( class Base '' ) cil managed { IL_0000: ldarg.1 IL_0001: brfalse.s IL_002d IL_0003: ldarg.0 IL_0004: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_0009: ldarg.1 IL_000a: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000f: call bool [mscorlib]System.Type::op_Equality(class [mscorlib]System.Type, class [mscorlib]System.Type) IL_0014: brfalse.s IL_002d IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: ldarg.1 IL_0022: ldfld int32 Base::'<i>k__BackingField' IL_0027: callvirt instance bool class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::Equals(!0, !0) IL_002c: ret IL_002d: ldc.i4.0 IL_002e: ret } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base '' ) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld int32 Base::'<i>k__BackingField' IL_000d: stfld int32 Base::'<i>k__BackingField' IL_0012: ret } .method public hidebysig instance void Deconstruct ( [out] int32& i ) cil managed { IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call instance int32 Base::get_i() IL_0007: stind.i4 IL_0008: ret } .method public hidebysig instance void Clone () cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::Write(string) IL_000a: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type Base::get_EqualityContract() } .property instance int32 i() { .get instance int32 Base::get_i() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) Base::set_i(int32) } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi abstract sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends [mscorlib]System.Object { } "; var src = @" record R(int i) : Base(i); public class C { public static void Main() { var r = new R(1); r.Clone(); } } "; var comp = CreateCompilationWithIL(src, il, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); // Note: we do load the Clone method from metadata } [Fact] public void Clone_01() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_02() { var src = @" sealed abstract record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // sealed abstract record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_03() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); } [Fact] public void Clone_04() { var src = @" record C1; sealed abstract record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // sealed abstract record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_05_IntReturnType_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_06_IntReturnType_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_07_Ambiguous_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_08_Ambiguous_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_09_AmbiguousReverseOrder_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_10_AmbiguousReverseOrder_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_11() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_12() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_12", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void Clone_13() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_13", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" class Program { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); } [Fact] public void Clone_14() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_15() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_15", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (2,8): error CS8869: 'C.Equals(object?)' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'C.GetHashCode()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'C.ToString()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 8), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new C(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22), // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (8,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c1.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9), // (9,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c2.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9) ); } [Fact] public void Clone_16() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_16", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" record D(int X) : C(X) { public static void Main() { var c1 = new D(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); } [Fact] public void Clone_17_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_18_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_19() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'C.<Clone>$()': cannot override inherited member 'B.<Clone>$()' because it is sealed // public record C : B { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.<Clone>$()", "B.<Clone>$()").WithLocation(2, 15) ); } [Fact, WorkItem(47093, "https://github.com/dotnet/roslyn/issues/47093")] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); abstract record C1; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); record Base; abstract record C1 : Base; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendStringAndChar() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendChar); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_Empty_Sealed() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); sealed record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact] public void ToString_AbstractRecord() { var src = @" var c2 = new C2(42, 43); System.Console.Write(c2.ToString()); abstract record C1(int I1); sealed record C2(int I1, int I2) : C1(I1); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2 { I1 = 42, I2 = 43 }", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public ref int P3 { get => ref field; } public event System.Action a; private int field1 = 100; internal int field2 = 100; protected int field3 = 100; private protected int field4 = 100; internal protected int field5 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; protected int Property3 { get; set; } = 100; private protected int Property4 { get; set; } = 100; internal protected int Property5 { get; set; } = 100; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43, P3 = 44 }", verify: Verification.Skipped /* init-only */); comp.VerifyEmitDiagnostics( // (12,32): warning CS0067: The event 'C1.a' is never used // public event System.Action a; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "a", isSuppressed: false).WithArguments("C1.a").WithLocation(12, 32), // (14,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1", isSuppressed: false).WithArguments("C1.field1").WithLocation(14, 17) ); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenVirtualProperty_NoRepetition() { var src = @" System.Console.WriteLine(new B() { P = 2 }.ToString()); abstract record A { public virtual int P { get; set; } } record B : A { public override int P { get; set; } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B { P = 2 }"); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenAbstractProperty_NoRepetition() { var src = @" System.Console.Write(new B1() { P = 1 }); System.Console.Write("" ""); System.Console.Write(new B2(2)); abstract record A1 { public abstract int P { get; set; } } record B1 : A1 { public override int P { get; set; } } abstract record A2(int P); record B2(int P) : A2(P); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B1 { P = 1 } B2 { P = 2 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_ErrorBase() { var src = @" record C2: Error; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C2.ToString()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.EqualityContract': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C2.Equals(object?)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C2.GetHashCode()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record C2: Error; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 12) ); } [Fact, WorkItem(49263, "https://github.com/dotnet/roslyn/issues/49263")] public void ToString_SelfReferentialBase() { var src = @" record R : R; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0146: Circular base type dependency involving 'R' and 'R' // record R : R; Diagnostic(ErrorCode.ERR_CircularBase, "R").WithArguments("R", "R").WithLocation(2, 8), // (2,8): error CS0115: 'R.ToString()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R.EqualityContract': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R.Equals(object?)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R.GetHashCode()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R.PrintMembers(StringBuilder)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_Empty_AbstractSealed() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record C1 { public int field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""int C1.field"" IL_0018: constrained. ""int"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""T C1<T>.field"" IL_0018: constrained. ""T"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record C1 { public string field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 32 (0x20) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldc.i4.1 IL_001f: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_Unconstrained() { var src = @" var c1 = new C1<string>() { field = ""hello"" }; System.Console.Write(c1.ToString()); System.Console.Write("" ""); var c2 = new C1<int>() { field = 42 }; System.Console.Write(c2.ToString()); record C1<T> { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello } C1 { field = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""T C1<T>.field"" IL_0018: box ""T"" IL_001d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0022: pop IL_0023: ldc.i4.1 IL_0024: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ErrorType() { var src = @" record C1 { public Error field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // public Error field; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 12), // (4,18): warning CS0649: Field 'C1.field' is never assigned to, and will always have its default value null // public Error field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C1.field", "null").WithLocation(4, 18) ); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1() { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record C1 { public string field1; public string field2; private string field3; internal string field4; protected string field5; protected internal string field6; private protected string field7; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (10,20): warning CS0169: The field 'C1.field3' is never used // private string field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "field3").WithArguments("C1.field3").WithLocation(10, 20), // (11,21): warning CS0649: Field 'C1.field4' is never assigned to, and will always have its default value null // internal string field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field4").WithArguments("C1.field4", "null").WithLocation(11, 21), // (12,22): warning CS0649: Field 'C1.field5' is never assigned to, and will always have its default value null // protected string field5; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field5").WithArguments("C1.field5", "null").WithLocation(12, 22), // (13,31): warning CS0649: Field 'C1.field6' is never assigned to, and will always have its default value null // protected internal string field6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field6").WithArguments("C1.field6", "null").WithLocation(13, 31), // (14,30): warning CS0649: Field 'C1.field7' is never assigned to, and will always have its default value null // private protected string field7; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field7").WithArguments("C1.field7", "null").WithLocation(14, 30) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 57 (0x39) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field1 = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field1"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldarg.1 IL_001f: ldstr "", field2 = "" IL_0024: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0029: pop IL_002a: ldarg.1 IL_002b: ldarg.0 IL_002c: ldfld ""string C1.field2"" IL_0031: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0036: pop IL_0037: ldc.i4.1 IL_0038: ret } "); } [Fact] public void ToString_TopLevelRecord_OneProperty() { var src = @" var c1 = new C1(Property: 42); System.Console.Write(c1.ToString()); record C1(int Property) { private int Property2; internal int Property3; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,17): warning CS0169: The field 'C1.Property2' is never used // private int Property2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Property2").WithArguments("C1.Property2").WithLocation(7, 17), // (8,18): warning CS0649: Field 'C1.Property3' is never assigned to, and will always have its default value 0 // internal int Property3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Property3").WithArguments("C1.Property3", "0").WithLocation(8, 18) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { Property = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 46 (0x2e) .maxstack 2 .locals init (int V_0) IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""Property = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: call ""int C1.Property.get"" IL_0018: stloc.0 IL_0019: ldloca.s V_0 IL_001b: constrained. ""int"" IL_0021: callvirt ""string object.ToString()"" IL_0026: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_002b: pop IL_002c: ldc.i4.1 IL_002d: ret }"); } [Fact] public void ToString_TopLevelRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1<int, string>(42, null) { field1 = 43, field2 = ""hi"" }; System.Console.Write(c1.ToString()); record C1<T1, T2>(T1 Property1, T2 Property2) { public T1 field1; public T2 field2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { Property1 = 42, Property2 = , field1 = 43, field2 = hi }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1(42, 43) { A2 = 100, B2 = 101 }; System.Console.Write(c1.ToString()); record Base(int A1) { public int A2; } record C1(int A1, int B1) : Base(A1) { public int B2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { A1 = 42, A2 = 100, B1 = 43, B2 = 101 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 98 (0x62) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: brfalse.s IL_0015 IL_0009: ldarg.1 IL_000a: ldstr "", "" IL_000f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0014: pop IL_0015: ldarg.1 IL_0016: ldstr ""B1 = "" IL_001b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0020: pop IL_0021: ldarg.1 IL_0022: ldarg.0 IL_0023: call ""int C1.B1.get"" IL_0028: stloc.0 IL_0029: ldloca.s V_0 IL_002b: constrained. ""int"" IL_0031: callvirt ""string object.ToString()"" IL_0036: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_003b: pop IL_003c: ldarg.1 IL_003d: ldstr "", B2 = "" IL_0042: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0047: pop IL_0048: ldarg.1 IL_0049: ldarg.0 IL_004a: ldflda ""int C1.B2"" IL_004f: constrained. ""int"" IL_0055: callvirt ""string object.ToString()"" IL_005a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_005f: pop IL_0060: ldc.i4.1 IL_0061: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractSealed() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var print = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_DerivedRecord_BaseHasSealedToString(bool usePreview) { var src = @" var c = new C2(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9, options: TestOptions.DebugExe); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } else { comp.VerifyEmitDiagnostics( // (7,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => "C1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(7, 35) ); } } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseTriesToOverride() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public override string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (11,28): error CS0239: 'C2.ToString()': cannot override inherited member 'C1.ToString()' because it is sealed // public override string ToString() => "C2"; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "ToString").WithArguments("C2.ToString()", "C1.ToString()").WithLocation(11, 28) ); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringPrivate() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { private new string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringNonSealed() { var src = @" C3 c3 = new C3(); System.Console.Write(c3.ToString()); C1 c1 = c3; System.Console.Write(c1.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new virtual string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentSignature() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public string ToString(int n) => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentReturnType() { var src = @" C1 c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new int ToString() => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_ReverseOrder() { var src = @" var c1 = new C1(42, 43) { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); record Base(int A2) { public int A1; } record C1(int A2, int B2) : Base(A2) { public int B1; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A2 = 42, A1 = 100, B2 = 43, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int A1; } "; var src2 = @" partial record C1 { public int B1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A1 = 100, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial_ReverseOrder() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int B1; } "; var src2 = @" partial record C1 { public int A1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { B1 = 101, A1 = 100 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_BadBase_MissingToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""RAN"" IL_0005: ret } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void A::.ctor() IL_0006: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } // no override for ToString } "; var source = @" var c = new C(); System.Console.Write(c); public record C : B { public override string ToString() => base.ToString(); } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] public void ToString_BadBase_PrintMembersSealed() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method final family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.PrintMembers(StringBuilder)': cannot override inherited member 'A.PrintMembers(StringBuilder)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersInaccessible() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method private hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.PrintMembers(StringBuilder)': return type must be 'int' to match overridden member 'A.PrintMembers(StringBuilder)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)", "int").WithLocation(2, 15) ); } [Fact] public void EqualityContract_BadBase_ReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance int32 get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 EqualityContract() { .get instance int32 A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersIsAmbiguous() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_MissingPrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_DuplicatePrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_PrintMembersNotOverriddenInBase() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } // no override for PrintMembers } "; var source = @" public record C : B { protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,29): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(4, 29) ); var source2 = @" public record C : B; "; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public record C : B; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersWithModOpt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var print = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean B.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.ToTestDisplayString()); Assert.Equal("System.Boolean A.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.OverriddenMethod.ToTestDisplayString()); } [Fact] public void ToString_BadBase_NewToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.ToString()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.ToString()").WithLocation(2, 15) ); } [Fact] public void ToString_NewToString_SealedBaseToString() { var source = @" B b = new B(); System.Console.Write(b.ToString()); A a = b; System.Console.Write(a.ToString()); public record A { public sealed override string ToString() => ""A""; } public record B : A { public new string ToString() => ""B""; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "BA"); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_BadBase_SealedToString(bool usePreview) { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""A"" IL_0001: ret } } "; var source = @" var b = new B(); System.Console.Write(b.ToString()); public record B : A { }"; var comp = CreateCompilationWithIL( new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "A"); } else { comp.VerifyEmitDiagnostics( // (5,15): error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# 9.0. Please use language version '10.0' or greater. // public record B : A { Diagnostic(ErrorCode.ERR_InheritingFromRecordWithSealedToString, "B").WithArguments("9.0", "10.0").WithLocation(5, 15) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_TopLevelRecord_UserDefinedToString_Sealed(bool usePreview) { var src = @" record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); } else { comp.VerifyEmitDiagnostics( // (4,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(4, 35) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed_InSealedRecord() { var src = @" sealed record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record C1 { protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 23) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record C1 { protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 27) ); } [Fact] public void ToString_UserDefinedPrintMembers_Sealed() { var src = @" record C1(int I1); record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8872: 'C2.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 36) ); } [Fact] public void ToString_UserDefinedPrintMembers_NonVirtual() { var src = @" record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_SealedInSealedRecord() { var src = @" record C1(int I1); sealed record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" sealed record C { private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C.PrintMembers(StringBuilder)' may not be static. // private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN }"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" record C1 { public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility_SealedRecord() { var src = @" sealed record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): warning CS0628: 'C1.PrintMembers(StringBuilder)': new protected member declared in sealed type // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20), // (4,20): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_DerivedRecord_WrongAccessibility() { var src = @" record B; record C1 : B { public bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,17): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 17), // (5,17): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): warning CS0114: 'C1.PrintMembers(StringBuilder)' hides inherited member 'B.PrintMembers(StringBuilder)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers_New() { var src = @" record B; record C1 : B { protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,32): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 32) ); } [Fact] public void ToString_TopLevelRecord_EscapedNamed() { var src = @" var c1 = new @base(); System.Console.Write(c1.ToString()); record @base; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "base { }"); } [Fact] public void ToString_DerivedDerivedRecord() { var src = @" var r1 = new R1(1); System.Console.Write(r1.ToString()); System.Console.Write("" ""); var r2 = new R2(10, 11); System.Console.Write(r2.ToString()); System.Console.Write("" ""); var r3 = new R3(20, 21, 22); System.Console.Write(r3.ToString()); record R1(int I1); record R2(int I1, int I2) : R1(I1); record R3(int I1, int I2, int I3) : R2(I1, I2); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "R1 { I1 = 1 } R2 { I1 = 10, I2 = 11 } R3 { I1 = 20, I2 = 21, I3 = 22 }", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr24() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); var clone = verifier.Compilation.GetMember("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal("<Clone>$", clone.Name); } [Fact] public void WithExpr25() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr26() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr27() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr28() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr29() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void AccessibilityOfBaseCtor_01() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y); "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] public void AccessibilityOfBaseCtor_02() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y) {} "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_03() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_04() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_05() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_06() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExprNestedErrors() { var src = @" class C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = """"-3 }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(8, 13), // (8,26): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'int' // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, @"""""-3").WithArguments("-", "string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprNoExpressionToPropertyTypeConversion() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """" }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprPropertyInaccessibleSet() { var src = @" record C { public int X { get; private set; } } class D { public static void Main() { var c = new C(); c = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0272: The property or indexer 'C.X' cannot be used in this context because the set accessor is inaccessible // c = c with { X = 0 }; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "X").WithArguments("C.X").WithLocation(11, 22) ); } [Fact] public void WithExprSideEffects1() { var src = @" using System; record C(int X, int Y, int Z) { public static void Main() { var c = new C(0, 1, 2); c = c with { Y = W(""Y""), X = W(""X"") }; } public static int W(string s) { Console.WriteLine(s); return 0; } } "; var verifier = CompileAndVerify(src, expectedOutput: @" Y X").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 47 (0x2f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""C..ctor(int, int, int)"" IL_0008: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000d: dup IL_000e: ldstr ""Y"" IL_0013: call ""int C.W(string)"" IL_0018: callvirt ""void C.Y.init"" IL_001d: dup IL_001e: ldstr ""X"" IL_0023: call ""int C.W(string)"" IL_0028: callvirt ""void C.X.init"" IL_002d: pop IL_002e: ret }"); var comp = (CSharpCompilation)verifier.Compilation; var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { Y ... = W(""X"") }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ Y = W(""Y"" ... = W(""X"") }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Y') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, 1, 2)') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Z) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with ... = W(""X"") };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with ... = W(""X"") }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void WithExprConversions1() { var src = @" using System; record C(long X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = 11 }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000c: dup IL_000d: ldc.i4.s 11 IL_000f: conv.i8 IL_0010: callvirt ""void C.X.init"" IL_0015: callvirt ""long C.X.get"" IL_001a: call ""void System.Console.WriteLine(long)"" IL_001f: ret }"); } [Fact] public void WithExprConversions2() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator long(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 44 (0x2c) .maxstack 3 .locals init (S V_0) //s IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 11 IL_000b: call ""S..ctor(int)"" IL_0010: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: dup IL_0016: ldloc.0 IL_0017: call ""long S.op_Implicit(S)"" IL_001c: callvirt ""void C.X.init"" IL_0021: callvirt ""long C.X.get"" IL_0026: call ""void System.Console.WriteLine(long)"" IL_002b: ret }"); } [Fact] public void WithExprConversions3() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = (int)s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); } [Fact] public void WithExprConversions4() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator long(S s) => s._i; } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (19,41): error CS0266: Cannot implicitly convert type 'S' to 'long'. An explicit conversion exists (are you missing a cast?) // Console.WriteLine((c with { X = s }).X); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("S", "long").WithLocation(19, 41) ); } [Fact] public void WithExprConversions5() { var src = @" using System; record C(object X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = ""abc"" }).X); } }"; CompileAndVerify(src, expectedOutput: "abc").VerifyDiagnostics(); } [Fact] public void WithExprConversions6() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C { private readonly long _x; public long X { get => _x; init { Console.WriteLine(""set""); _x = value; } } public static void Main() { var c = new C(); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion set 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (S V_0) //s IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldc.i4.s 11 IL_0009: call ""S..ctor(int)"" IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldloc.0 IL_0015: call ""int S.op_Implicit(S)"" IL_001a: conv.i8 IL_001b: callvirt ""void C.X.init"" IL_0020: callvirt ""long C.X.get"" IL_0025: call ""void System.Console.WriteLine(long)"" IL_002a: ret }"); } [Fact] public void WithExprStaticProperty() { var src = @" record C { public static int X { get; set; } public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS0176: Member 'C.X' cannot be accessed with an instance reference; qualify it with a type name instead // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("C.X").WithLocation(9, 22) ); } [Fact] public void WithExprMethodAsArgument() { var src = @" record C { public int X() => 0; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(9, 22) ); } [Fact] public void WithExprStaticWithMethod() { var src = @" class C { public int X = 0; public static C Clone() => null; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(10, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprStaticWithMethod2() { var src = @" class B { public B Clone() => null; } class C : B { public int X = 0; public static new C Clone() => null; // static public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0266: Cannot implicitly convert type 'B' to 'C'. An explicit conversion exists (are you missing a cast?) // c = c with { }; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c with { }").WithArguments("B", "C").WithLocation(13, 13), // (14,22): error CS0117: 'B' does not contain a definition for 'X' // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("B", "X").WithLocation(14, 22) ); } [Fact] public void WithExprBadMemberBadType() { var src = @" record C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = ""a"" }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "a" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""a""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprCloneReturnDifferent() { var src = @" class B { public int X { get; init; } } class C : B { public B Clone() => new B(); public static void Main() { var c = new C(); var b = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithSemanticModel1() { var src = @" record C(int X, string Y) { public static void Main() { var c = new C(0, ""a""); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(withExpr); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsRecord); Assert.True(c.ISymbol.Equals(typeInfo.Type)); var x = c.GetMembers("X").Single(); var xId = withExpr.DescendantNodes().Single(id => id.ToString() == "X"); var symbolInfo = model.GetSymbolInfo(xId); Assert.True(x.ISymbol.Equals(symbolInfo.Symbol)); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.String Y)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, ""a"")') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '""a""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""a"") (Syntax: '""a""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { X = 2 }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_01() { var src = @" class C { int X { get; set; } public static void Main() { var c = new C(); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Children(1): ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_02() { var source = @"#nullable enable class R { public object? P { get; set; } } class Program { static void Main() { R r = new R(); _ = r with { P = 2 }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8858: The receiver type 'R' is not a valid record type. // _ = r with { P = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "r").WithArguments("R").WithLocation(11, 13)); } [Fact] public void WithBadExprArg() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { 5 }; c = c with { { X = 2 } }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS0747: Invalid initializer member declarator // c = c with { 5 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "5").WithLocation(8, 22), // (9,22): error CS1513: } expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(9, 22), // (9,22): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(9, 22), // (9,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.X' // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_ObjectRequired, "X").WithArguments("C.X").WithLocation(9, 24), // (9,30): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(9, 30), // (9,33): error CS1597: Semicolon after method or accessor block is not valid // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(9, 33), // (11,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(11, 1) ); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); VerifyClone(model); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { 5 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ 5 }') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '5') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5')"); var withExpr2 = root.DescendantNodes().OfType<WithExpressionSyntax>().Skip(1).Single(); comp.VerifyOperationTree(withExpr2, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { ') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ ') Initializers(0)"); } [Fact] public void WithExpr_DefiniteAssignment_01() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = y = 42 }; y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_02() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { X = z = 42, Y = z.ToString() }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_03() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { Y = z.ToString(), X = z = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,26): error CS0165: Use of unassigned local variable 'z' // _ = b with { Y = z.ToString(), X = z = 42 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(7, 26)); } [Fact] public void WithExpr_DefiniteAssignment_04() { var src = @" record B(int X) { static void M() { B b; _ = (b = new B(42)) with { X = b.X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_05() { var src = @" record B(int X) { static void M() { B b; _ = new B(b.X) with { X = (b = new B(42)).X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,19): error CS0165: Use of unassigned local variable 'b' // _ = new B(b.X) with { X = new B(42).X }; Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(7, 19)); } [Fact] public void WithExpr_DefiniteAssignment_06() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = M(out y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_07() { var src = @" record B(int X) { static void M(B b) { _ = b with { X = M(out int y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact] public void WithExpr_NullableAnalysis_04() { var src = @" #nullable enable record B(int X) { static void M1(B? b) { var b1 = b with { X = 42 }; // 1 _ = b.ToString(); _ = b1.ToString(); } static void M2(B? b) { (b with { X = 42 }).ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,18): warning CS8602: Dereference of a possibly null reference. // var b1 = b with { X = 42 }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 18), // (14,10): warning CS8602: Dereference of a possibly null reference. // (b with { X = 42 }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(14, 10)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable record B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_07() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([AllowNull] string X) // 1 { static void M1(B b) { b.X.ToString(); b = b with { X = null }; // 2 b.X.ToString(); // 3 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,10): warning CS8601: Possible null reference assignment. // record B([AllowNull] string X) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "[AllowNull] string X").WithLocation(5, 10), // (10,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // b = b with { X = null }; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 26), // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_08() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([property: AllowNull][AllowNull] string X) { static void M1(B b) { b.X.ToString(); b = b with { X = null }; b.X.ToString(); // 1 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact] public void WithExpr_NullableAnalysis_09() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { B b2 = b1 with { X = ""hello"" }; B b3 = b1 with { Y = ""world"" }; B b4 = b2 with { Y = ""world"" }; b1.X.ToString(); // 1 b1.Y.ToString(); // 2 b2.X.ToString(); b2.Y.ToString(); // 3 b3.X.ToString(); // 4 b3.Y.ToString(); b4.X.ToString(); b4.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b1.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.X").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // b1.Y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Y").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // b2.Y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Y").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // b3.X.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_10() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { string? local = ""hello""; _ = b1 with { X = local = null, Y = local.ToString() // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // Y = local.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local").WithLocation(11, 17)); } [Fact] public void WithExpr_NullableAnalysis_11() { var src = @" #nullable enable record B(string X, string Y) { static string M0(out string? s) { s = null; return ""hello""; } static void M1(B b1) { string? local = ""world""; _ = b1 with { X = M0(out local), Y = local // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): warning CS8601: Possible null reference assignment. // Y = local // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "local").WithLocation(13, 17)); } [Fact] public void WithExpr_NullableAnalysis_VariantClone() { var src = @" #nullable enable record A { public string? Y { get; init; } public string? Z { get; init; } } record B(string? X) : A { public new string Z { get; init; } = ""zed""; static void M1(B b1) { b1.Z.ToString(); (b1 with { Y = ""hello"" }).Y.ToString(); (b1 with { Y = ""hello"" }).Z.ToString(); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(10, 21), // (11,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(11, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_MaybeNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: MaybeNull] public B Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(new[] { src, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(13, 21), // (14,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(14, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NotNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: NotNull] public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; (b1 with { X = null }).ToString(); } } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone_NoInitializers() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; (b1 with { }).ToString(); // 1 } } "; var comp = CreateCompilation(src); // Note: we expect to give a warning on `// 1`, but do not currently // due to limitations of object initializer analysis. // Tracking in https://github.com/dotnet/roslyn/issues/44759 comp.VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord() { var src = @" using System; record C { public int X { get; set; } public string Y { get; init; } public long Z; public event Action E; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; E = other.E; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3, E = () => { } }; var c2 = c with {}; Console.WriteLine(c.Equals(c2)); Console.WriteLine(ReferenceEquals(c, c2)); Console.WriteLine(c2.X); Console.WriteLine(c2.Y); Console.WriteLine(c2.Z); Console.WriteLine(ReferenceEquals(c.E, c2.E)); var c3 = c with { Y = ""3"", X = 2 }; Console.WriteLine(c.Y); Console.WriteLine(c3.Y); Console.WriteLine(c.X); Console.WriteLine(c3.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" True False 1 2 3 True 2 3 1 2").VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord2() { var comp1 = CreateCompilation(@" public record C { public int X { get; set; } public string Y { get; init; } public long Z; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; } }"); var verifier = CompileAndVerify(@" class D { public C M(C c) => c with { X = 5, Y = ""a"", Z = 2, }; }", references: new[] { comp1.EmitToImageReference() }).VerifyDiagnostics(); verifier.VerifyIL("D.M", @" { // Code size 33 (0x21) .maxstack 3 IL_0000: ldarg.1 IL_0001: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0006: dup IL_0007: ldc.i4.5 IL_0008: callvirt ""void C.X.set"" IL_000d: dup IL_000e: ldstr ""a"" IL_0013: callvirt ""void C.Y.init"" IL_0018: dup IL_0019: ldc.i4.2 IL_001a: conv.i8 IL_001b: stfld ""long C.Z"" IL_0020: ret }"); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 51 (0x33) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""ref int C.X.get"" IL_000c: ldc.i4.5 IL_000d: stind.i4 IL_000e: dup IL_000f: callvirt ""ref int C.X.get"" IL_0014: ldind.i4 IL_0015: call ""void System.Console.WriteLine(int)"" IL_001a: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_001f: dup IL_0020: callvirt ""ref int C.X.get"" IL_0025: ldc.i4.1 IL_0026: stind.i4 IL_0027: callvirt ""ref int C.X.get"" IL_002c: ldind.i4 IL_002d: call ""void System.Console.WriteLine(int)"" IL_0032: ret }"); } [Fact] public void WithExprAssignToRef2() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X { get => ref _a[0]; set { } } public static void Main() { var a = new[] { 0 }; var c = new C(0) { X = ref a[0] }; Console.WriteLine(c.X); c = c with { X = ref a[0] }; Console.WriteLine(c.X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,9): error CS8147: Properties which return by reference cannot have set accessors // set { } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.X.set").WithLocation(9, 9), // (15,32): error CS1525: Invalid expression term 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref a[0]").WithArguments("ref").WithLocation(15, 32), // (15,32): error CS1073: Unexpected token 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(15, 32), // (17,26): error CS1073: Unexpected token 'ref' // c = c with { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(17, 26) ); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_ValEscape() { var text = @" using System; record R { public S1 Property { set { throw null; } } } class Program { static void Main() { var r = new R(); Span<int> local = stackalloc int[1]; _ = r with { Property = MayWrap(ref local) }; _ = new R() { Property = MayWrap(ref local) }; } static S1 MayWrap(ref Span<int> arg) { return default; } } ref struct S1 { public ref int this[int i] => throw null; } "; CreateCompilationWithMscorlibAndSpan(text).VerifyDiagnostics(); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_01() { var source = @"record A { internal A() { } public object P1 { get; set; } internal object P2 { get; set; } protected internal object P3 { get; set; } protected object P4 { get; set; } private protected object P5 { get; set; } private object P6 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P6 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_02() { var source = @"record A { internal A() { } private protected object P1 { get; set; } private object P2 { get; set; } private record B(object P1, object P2) : A { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 29), // (6,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 40) ); var actualMembers = GetProperties(comp, "A.B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type A.B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_03(bool useCompilationReference) { var sourceA = @"public record A { public A() { } internal object P { get; set; } } public record B(object Q) : A { public B() : this(null) { } } record C1(object P, object Q) : B { }"; var comp = CreateCompilation(sourceA); AssertEx.Equal(new[] { "System.Type C1.EqualityContract { get; }" }, GetProperties(comp, "C1").ToTestDisplayStrings()); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C2(object P, object Q) : B { }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,28): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C2(object P, object Q) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 28) ); AssertEx.Equal(new[] { "System.Type C2.EqualityContract { get; }", "System.Object C2.P { get; init; }" }, GetProperties(comp, "C2").ToTestDisplayStrings()); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_04() { var source = @"record A { internal A() { } public object P1 { get { return null; } set { } } public object P2 { get; init; } public object P3 { get; } public object P4 { set { } } public virtual object P5 { get; set; } public static object P6 { get; set; } public ref object P7 => throw null; } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(12, 17), // (12,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(12, 28), // (12,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(12, 39), // (12,50): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "object", "P4").WithLocation(12, 50), // (12,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(12, 50), // (12,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(12, 61), // (12,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(12, 72), // (12,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(12, 72), // (12,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(12, 83)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_05() { var source = @"record A { internal A() { } public object P1 { get; set; } public int P2 { get; set; } } record B(int P1, object P2) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "int", "P1").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(7, 14), // (7,25): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "object", "P2").WithLocation(7, 25), // (7,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(7, 25)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_06() { var source = @"record A { internal int X { get; set; } internal int Y { set { } } internal int Z; } record B(int X, int Y, int Z) : A { } class Program { static void Main() { var b = new B(1, 2, 3); b.X = 4; b.Y = 5; b.Z = 6; ((A)b).X = 7; ((A)b).Y = 8; ((A)b).Z = 9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): error CS8866: Record member 'A.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("A.Y", "int", "Y").WithLocation(7, 21), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (7,24): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int Z").WithArguments("positional fields in records", "10.0").WithLocation(7, 24), // (7,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(7, 28)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_07() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } } abstract record B1(int X, int Y) : A { } record B2(int X, int Y) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS0546: 'B1.X.init': cannot override because 'A.X' does not have an overridable set accessor // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B1.X.init", "A.X").WithLocation(6, 24), // (6,31): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 31), // (9,15): error CS0546: 'B2.X.init': cannot override because 'A.X' does not have an overridable set accessor // record B2(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B2.X.init", "A.X").WithLocation(9, 15), // (9,22): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B2(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 22)); AssertEx.Equal(new[] { "System.Type B1.EqualityContract { get; }", "System.Int32 B1.X { get; init; }" }, GetProperties(comp, "B1").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type B2.EqualityContract { get; }", "System.Int32 B2.X { get; init; }" }, GetProperties(comp, "B2").ToTestDisplayStrings()); var b1Ctor = comp.GetTypeByMetadataName("B1")!.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("B1..ctor(System.Int32 X, System.Int32 Y)", b1Ctor.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, b1Ctor.DeclaredAccessibility); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_08() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } public virtual int Z { get; } } abstract record B : A { public override abstract int Y { get; } } record C(int X, int Y, int Z) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): error CS0546: 'C.X.init': cannot override because 'A.X' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("C.X.init", "A.X").WithLocation(11, 14), // (11,21): error CS0546: 'C.Y.init': cannot override because 'B.Y' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "Y").WithArguments("C.Y.init", "B.Y").WithLocation(11, 21), // (11,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.Y { get; init; }" }, actualMembers); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void Inheritance_09() { var source = @"abstract record C(int X, int Y) { public abstract int X { get; } public virtual int Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,23): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(1, 23), // (1,30): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(1, 30) ); NamedTypeSymbol c = comp.GetMember<NamedTypeSymbol>("C"); var actualMembers = c.GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; }", "System.Int32 C.X.get", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y { get; }", "System.Int32 C.Y.get", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "X", "get_X", "<Y>k__BackingField", "Y", "get_Y", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, c.GetPublicSymbol().MemberNames); var expectedCtors = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", }; AssertEx.Equal(expectedCtors, c.GetPublicSymbol().Constructors.ToTestDisplayStrings()); } [Fact] public void Inheritance_10() { var source = @"using System; interface IA { int X { get; } } interface IB { int Y { get; } } record C(int X, int Y) : IA, IB { } class Program { static void Main() { var c = new C(1, 2); Console.WriteLine(""{0}, {1}"", c.X, c.Y); Console.WriteLine(""{0}, {1}"", ((IA)c).X, ((IB)c).Y); } }"; CompileAndVerify(source, expectedOutput: @"1, 2 1, 2").VerifyDiagnostics(); } [Fact] public void Inheritance_11() { var source = @"interface IA { int X { get; } } interface IB { object Y { get; set; } } record C(object X, object Y) : IA, IB { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,32): error CS0738: 'C' does not implement interface member 'IA.X'. 'C.X' cannot implement 'IA.X' because it does not have the matching return type of 'int'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "IA").WithArguments("C", "IA.X", "C.X", "int").WithLocation(9, 32), // (9,36): error CS8854: 'C' does not implement interface member 'IB.Y.set'. 'C.Y.init' cannot implement 'IB.Y.set'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "IB").WithArguments("C", "IB.Y.set", "C.Y.init").WithLocation(9, 36) ); } [Fact] public void Inheritance_12() { var source = @"record A { public object X { get; } public object Y { get; } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(6, 17), // (6,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 27), // (8,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(8, 19), // (9,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(9, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_13() { var source = @"record A(object X, object Y) { internal A() : this(null, null) { } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 17), // (5,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 27), // (7,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(7, 19), // (8,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(8, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_14() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B : A { public new int P1 { get; } public new int P2 { get; } } record C(object P1, int P2, object P3, int P4) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(13, 17), // (13,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(13, 17), // (13,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(13, 25), // (13,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(13, 36), // (13,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(13, 44), // (13,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(13, 44)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_15() { var source = @"record C(int P1, object P2) { public object P1 { get; set; } public int P2 { get; set; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,14): error CS8866: Record member 'C.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("C.P1", "int", "P1").WithLocation(1, 14), // (1,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 14), // (1,25): error CS8866: Record member 'C.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("C.P2", "object", "P2").WithLocation(1, 25), // (1,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 25)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Int32 C.P2 { get; set; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_16() { var source = @"record A { public int P1 { get; } public int P2 { get; } public int P3 { get; } public int P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'int' to match positional parameter 'P2'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "int", "P2").WithLocation(8, 25), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(8, 36), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; }", "System.Object B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_17() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new int P1 { get; } public new int P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(8, 17), // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(8, 44), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Int32 B.P1 { get; }", "System.Int32 B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_18() { var source = @"record C(object P1, object P2, object P3, object P4, object P5) { public object P1 { get { return null; } set { } } public object P2 { get; } public object P3 { set { } } public static object P4 { get; set; } public ref object P5 => throw null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'C.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("C.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39), // (1,50): error CS8866: Record member 'C.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("C.P4", "object", "P4").WithLocation(1, 50), // (1,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(1, 50), // (1,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(1, 61)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Object C.P2 { get; }", "System.Object C.P3 { set; }", "System.Object C.P4 { get; set; }", "ref System.Object C.P5 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_19() { var source = @"#pragma warning disable 8618 #nullable enable record A { internal A() { } public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } } record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(15, 18), // (15,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(15, 31), // (15,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(15, 42), // (15,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(15, 56), // (15,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(15, 71), // (15,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(15, 92), // (15,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(15, 110), // (15,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(15, 122) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_20() { var source = @"#pragma warning disable 8618 #nullable enable record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) { public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(3, 18), // (3,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(3, 31), // (3,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(3, 42), // (3,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(3, 56), // (3,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(3, 71), // (3,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(3, 92), // (3,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(3, 110), // (3,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(3, 122) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; }", "dynamic[] C.P2 { get; }", "System.Object? C.P3 { get; }", "System.Object[] C.P4 { get; }", "(System.Int32 X, System.Int32 Y) C.P5 { get; }", "(System.Int32, System.Int32)[] C.P6 { get; }", "nint C.P7 { get; }", "System.UIntPtr[] C.P8 { get; }" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_21(bool useCompilationReference) { var sourceA = @"public record A { public object P1 { get; } internal object P2 { get; } } public record B : A { internal new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(sourceA); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B { } class Program { static void Main() { var c = new C(1, 2); System.Console.WriteLine(""({0}, {1})"", c.P1, c.P2); } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); var verifier = CompileAndVerify(comp, expectedOutput: "(, )").VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28) ); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""B..ctor()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ret }"); verifier.VerifyIL("Program.Main", @"{ // Code size 41 (0x29) .maxstack 3 .locals init (C V_0) //c IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ldc.i4.2 IL_0007: box ""int"" IL_000c: newobj ""C..ctor(object, object)"" IL_0011: stloc.0 IL_0012: ldstr ""({0}, {1})"" IL_0017: ldloc.0 IL_0018: callvirt ""object A.P1.get"" IL_001d: ldloc.0 IL_001e: callvirt ""object B.P2.get"" IL_0023: call ""void System.Console.WriteLine(string, object, object)"" IL_0028: ret }"); } [Fact] public void Inheritance_22() { var source = @"record A { public ref object P1 => throw null; public object P2 => throw null; } record B : A { public new object P1 => throw null; public new ref object P2 => throw null; } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_23() { var source = @"record A { public static object P1 { get; } public object P2 { get; } } record B : A { public new object P1 { get; } public new static object P2 { get; } } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(object P1, object P2) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "object", "P2").WithLocation(11, 28), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_24() { var source = @"record A { public object get_P() => null; public object set_Q() => null; } record B(object P, object Q) : A { } record C(object P) { public object get_P() => null; public object set_Q() => null; }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (9,17): error CS0082: Type 'C' already reserves a member called 'get_P' with the same parameter types // record C(object P) Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("get_P", "C").WithLocation(9, 17)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var expectedMembers = new[] { "B..ctor(System.Object P, System.Object Q)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Object B.<P>k__BackingField", "System.Object B.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.P.init", "System.Object B.P { get; init; }", "System.Object B.<Q>k__BackingField", "System.Object B.Q.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Q.init", "System.Object B.Q { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Object P, out System.Object Q)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings()); expectedMembers = new[] { "C..ctor(System.Object P)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Object C.<P>k__BackingField", "System.Object C.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.P.init", "System.Object C.P { get; init; }", "System.Object C.get_P()", "System.Object C.set_Q()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Object P)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Inheritance_25() { var sourceA = @"public record A { public class P1 { } internal object P2 = 2; public int P3(object o) => 3; internal int P4<T>(T t) => 4; }"; var sourceB = @"record B(object P1, object P2, object P3, object P4) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P2 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_26() { var sourceA = @"public record A { internal const int P = 4; }"; var sourceB = @"record B(object P) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record B(object P) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("A.P", "object", "P").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Fact] public void Inheritance_27() { var source = @"record A { public object P { get; } public object Q { get; set; } } record B(object get_P, object set_Q) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.get_P { get; init; }", "System.Object B.set_Q { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_28() { var source = @"interface I { object P { get; } } record A : I { object I.P => null; } record B(object P) : A { } record C(object P) : I { object I.P => null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; init; }", "System.Object C.I.P { get; }" }, GetProperties(comp, "C").ToTestDisplayStrings()); } [Fact] public void Inheritance_29() { var sourceA = @"Public Class A Public Property P(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property Q(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { object P { get; } }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Q { get; init; }", "System.Object B.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_30() { var sourceA = @"Public Class A Public ReadOnly Overloads Property P() As Object Get Return Nothing End Get End Property Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_31() { var sourceA = @"Public Class A Public ReadOnly Property P() As Object Get Return Nothing End Get End Property Public Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property R(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(a as A) End Sub End Class Public Class B Inherits A Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property R(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(b as B) MyBase.New(b) End Sub End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record C(object P, object Q, object R) : B { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'C.Equals(B?)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(B?)").WithLocation(1, 8), // (1,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'b' of 'B.B(B)' // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("b", "B.B(B)").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,42): error CS8864: Records may only inherit from object or another record // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_BadRecordBase, "B").WithLocation(1, 42) ); var actualMembers = GetProperties(compB, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.R { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_32() { var source = @"record A { public virtual object P1 { get; } public virtual object P2 { get; set; } public virtual object P3 { get; protected init; } public virtual object P4 { protected get; init; } public virtual object P5 { init { } } public virtual object P6 { set { } } public static object P7 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(11, 61), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61), // (11,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(11, 72), // (11,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(11, 72), // (11,83): error CS8866: Record member 'A.P7' must be a readable instance property or field of type 'object' to match positional parameter 'P7'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P7").WithArguments("A.P7", "object", "P7").WithLocation(11, 83), // (11,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(11, 83)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_33() { var source = @"abstract record A { public abstract object P1 { get; } public abstract object P2 { get; set; } public abstract object P3 { get; protected init; } public abstract object P4 { protected get; init; } public abstract object P5 { init; } public abstract object P6 { set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P6.set' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P6.set").WithLocation(10, 8), // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P5.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P5.init").WithLocation(10, 8), // (10,17): error CS0546: 'B.P1.init': cannot override because 'A.P1' does not have an overridable set accessor // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_NoSetToOverride, "P1").WithArguments("B.P1.init", "A.P1").WithLocation(10, 17), // (10,28): error CS8853: 'B.P2' must match by init-only of overridden member 'A.P2' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "P2").WithArguments("B.P2", "A.P2").WithLocation(10, 28), // (10,39): error CS0507: 'B.P3.init': cannot change access modifiers when overriding 'protected' inherited member 'A.P3.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P3").WithArguments("B.P3.init", "protected", "A.P3.init").WithLocation(10, 39), // (10,50): error CS0507: 'B.P4.get': cannot change access modifiers when overriding 'protected' inherited member 'A.P4.get' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P4").WithArguments("B.P4.get", "protected", "A.P4.get").WithLocation(10, 50), // (10,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(10, 61), // (10,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(10, 61), // (10,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(10, 72), // (10,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(10, 72)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; init; }", "System.Object B.P2 { get; init; }", "System.Object B.P3 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_34() { var source = @"abstract record A { public abstract object P1 { get; init; } public virtual object P2 { get; init; } } record B(string P1, string P2) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.init' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.init").WithLocation(6, 8), // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.get' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.get").WithLocation(6, 8), // (6,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'string' to match positional parameter 'P1'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "string", "P1").WithLocation(6, 17), // (6,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 17), // (6,28): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'string' to match positional parameter 'P2'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "string", "P2").WithLocation(6, 28), // (6,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 28)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_35() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; } public abstract object Y { get; init; } } record B(object X, object Y) : A(X, Y) { public override object X { get; } = X; } class Program { static void Main() { B b = new B(1, 2); A a = b; WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Y { get; init; }", "System.Object B.X { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.2 IL_0002: stfld ""object B.<Y>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""object B.<X>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""A..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object B.<Y>k__BackingField"" IL_000e: stfld ""object B.<Y>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object B.<X>k__BackingField"" IL_001a: stfld ""object B.<X>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object B.<X>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object B.<X>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object B.<Y>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object B.<X>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_36() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } } abstract record B : A { public abstract object Y { get; init; } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine(a.X); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) 1 (1, 2)").VerifyDiagnostics(); verifier.VerifyIL("A..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""A..ctor()"" IL_0006: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: call ""B..ctor()"" IL_0014: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object B.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_37() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; init; } public virtual object Y { get; init; } } abstract record B(object X, object Y) : A(X, Y) { public override abstract object X { get; init; } public override abstract object Y { get; init; } } record C(object X, object Y) : B(X, Y); class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object A.<Y>k__BackingField"" IL_000d: stfld ""object A.<Y>k__BackingField"" IL_0012: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""object A.<Y>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""object A.<Y>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""object A.<Y>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0026: add IL_0027: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""A..ctor(object, object)"" IL_0008: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""B..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_38() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } public abstract object Y { get; init; } } abstract record B : A { public new void X() { } public new struct Y { } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); A a = c; WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (9,21): error CS0533: 'B.X()' hides inherited abstract member 'A.X' // public new void X() { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "X").WithArguments("B.X()", "A.X").WithLocation(9, 21), // (10,23): error CS0533: 'B.Y' hides inherited abstract member 'A.Y' // public new struct Y { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Y").WithArguments("B.Y", "A.Y").WithLocation(10, 23), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.init").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.init").WithLocation(12, 8), // (12,17): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'object' to match positional parameter 'X'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "object", "X").WithLocation(12, 17), // (12,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 17), // (12,27): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'object' to match positional parameter 'Y'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "object", "Y").WithLocation(12, 27), // (12,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 27)); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", }, GetProperties(comp, "C").ToTestDisplayStrings()); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_39() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public abstract B extends A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void A::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class B A_1) { ldnull throw } .method public hidebysig specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public hidebysig instance object P() { ldnull ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record CA(object P) : A; record CB(object P) : B; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.get' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.get").WithLocation(2, 8), // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.init' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.init").WithLocation(2, 8), // (2,18): error CS8866: Record member 'B.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record CB(object P) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("B.P", "object", "P").WithLocation(2, 18), // (2,18): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record CB(object P) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 18)); AssertEx.Equal(new[] { "System.Type CA.EqualityContract { get; }", "System.Object CA.P { get; init; }" }, GetProperties(comp, "CA").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type CB.EqualityContract { get; }" }, GetProperties(comp, "CB").ToTestDisplayStrings()); } // Accessor names that do not match the property name. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_40() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::GetProperty1() } .property instance object P() { .get instance object A::GetProperty2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::SetProperty2(object) } .method family virtual instance class [mscorlib]System.Type GetProperty1() { ldnull ret } .method public abstract virtual instance object GetProperty2() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) SetProperty2(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "GetProperty1", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "GetProperty2", "SetProperty2"); } // Accessor names that do not match the property name and are not valid C# names. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_41() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::'EqualityContract<>get'() } .property instance object P() { .get instance object A::'P<>get'() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::'P<>set'(object) } .method family virtual instance class [mscorlib]System.Type 'EqualityContract<>get'() { ldnull ret } .method public abstract virtual instance object 'P<>get'() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) 'P<>set'(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "EqualityContract<>get", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "P<>get", "P<>set"); } private static void VerifyProperty(Symbol symbol, string propertyDescription, string? getterName, string? setterName) { var property = (PropertySymbol)symbol; Assert.Equal(propertyDescription, symbol.ToTestDisplayString()); VerifyAccessor(property.GetMethod, getterName); VerifyAccessor(property.SetMethod, setterName); } private static void VerifyAccessor(MethodSymbol? accessor, string? name) { Assert.Equal(name, accessor?.Name); if (accessor is object) { Assert.True(accessor.HasSpecialName); foreach (var parameter in accessor.Parameters) { Assert.Same(accessor, parameter.ContainingSymbol); } } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_42() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type modopt(int32) EqualityContract() { .get instance class [mscorlib]System.Type modopt(int32) A::get_EqualityContract() } .property instance object modopt(uint16) P() { .get instance object modopt(uint16) A::get_P() .set instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object modopt(uint16)) } .method family virtual instance class [mscorlib]System.Type modopt(int32) get_EqualityContract() { ldnull ret } .method public abstract virtual instance object modopt(uint16) get_P() { } .method public abstract virtual instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object modopt(uint16) 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); var property = (PropertySymbol)actualMembers[0]; Assert.Equal("System.Type modopt(System.Int32) B.EqualityContract { get; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Int32))); property = (PropertySymbol)actualMembers[1]; Assert.Equal("System.Object modopt(System.UInt16) B.P { get; init; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); verifyReturnType(property.SetMethod, CSharpCustomModifier.CreateRequired(comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit)), CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Byte))); verifyParameterType(property.SetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); static void verifyReturnType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var returnType = method.ReturnTypeWithAnnotations; Assert.True(method.OverriddenMethod.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); AssertEx.Equal(expectedModifiers, returnType.CustomModifiers); } static void verifyParameterType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var parameterType = method.Parameters[0].TypeWithAnnotations; Assert.True(method.OverriddenMethod.Parameters[0].TypeWithAnnotations.Equals(parameterType, TypeCompareKind.ConsiderEverything)); AssertEx.Equal(expectedModifiers, parameterType.CustomModifiers); } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_43() { var source = @"#nullable enable record A { protected virtual System.Type? EqualityContract => null; } record B : A { static void Main() { var b = new B(); _ = b.EqualityContract.ToString(); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); Assert.Equal("System.Type! B.EqualityContract { get; }", GetProperties(comp, "B").Single().ToTestDisplayString(includeNonNullable: true)); } // No EqualityContract property on base. [Fact] public void Inheritance_44() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { ldnull throw } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method public instance object get_P() { ldnull ret } .method public instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { ret } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record B : A; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [InlineData(false)] [InlineData(true)] public void CopyCtor(bool useCompilationReference) { var sourceA = @"public record B(object N1, object N2) { }"; var compA = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceA : new[] { sourceA, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); var verifierA = CompileAndVerify(compA, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifierA.VerifyIL("B..ctor(B)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object B.<N1>k__BackingField"" IL_000d: stfld ""object B.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object B.<N2>k__BackingField"" IL_0019: stfld ""object B.<N2>k__BackingField"" IL_001e: ret }"); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); System.Console.Write("" ""); var c3 = c1 with { P1 = 10, N1 = 30 }; System.Console.Write((c3.P1, c3.P2, c3.N1, c3.N2)); } }"; var compB = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceB : new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, targetFramework: TargetFramework.StandardLatest); var verifierB = CompileAndVerify(compB, expectedOutput: "(1, 2, 3, 4) (1, 2, 3, 4) (10, 2, 30, 4)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifierB.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); verifierA.VerifyIL($"B.{WellKnownMemberNames.CloneMethodName}()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""B..ctor(B)"" IL_0006: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithOtherOverload() { var source = @"public record B(object N1, object N2) { public B(C c) : this(30, 40) => throw null; } public record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = c1 with { P1 = 10, P2 = 20, N1 = 30, N2 = 40 }; System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4) (10, 20, 30, 40)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithObsoleteCopyConstructor() { var source = @"public record B(object N1, object N2) { [System.Obsolete(""Obsolete"", true)] public B(B b) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithParamsCopyConstructor() { var source = @"public record B(object N1, object N2) { public B(B b, params int[] i) : this(30, 40) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(source); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Object N1, System.Object N2)", "B..ctor(B b, params System.Int32[] i)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithInitializers() { var source = @"public record C(object N1, object N2) { private int field = 42; public int Property = 43; }"; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics( // (3,17): warning CS0414: The field 'C.field' is assigned but its value is never used // private int field = 42; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(3, 17) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 55 (0x37) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object C.<N1>k__BackingField"" IL_000d: stfld ""object C.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object C.<N2>k__BackingField"" IL_0019: stfld ""object C.<N2>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""int C.field"" IL_0025: stfld ""int C.field"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Property"" IL_0031: stfld ""int C.Property"" IL_0036: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_NotInRecordType() { var source = @"public class C { public object Property { get; set; } public int field = 42; public C(C c) { } } public class D : C { public int field2 = 43; public D(D d) : base(d) { } } "; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int C.field"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: ret }"); verifier.VerifyIL("D..ctor(D)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 43 IL_0003: stfld ""int D.field2"" IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: call ""C..ctor(C)"" IL_000f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject() { var source = @"public record C(int I) { public int I { get; set; } = 42; public C(C c) { } public static void Main() { var c = new C(1); c.I = 2; var c2 = new C(c); System.Console.Write((c.I, c2.I)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_WithFieldInitializer() { var source = @"public record C(int I) { public int I { get; set; } = 42; public int field = 43; public C(C c) { System.Console.Write("" RAN ""); } public static void Main() { var c = new C(1); c.I = 2; c.field = 100; System.Console.Write((c.I, c.field)); var c2 = new C(c); System.Console.Write((c2.I, c2.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 100) RAN (0, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr "" RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_GivesParameterToBase() { var source = @" public record C(object I) { public C(C c) : base(1) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(4, 21), // (4,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(4, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_WithSomeOtherConstructor() { var source = @" public record C(object I) { public C(int i) : this((object)null) { } public static void Main() { var c = new C((object)null); var c2 = new C(1); var c3 = new C(c); System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "RAN", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: call ""C..ctor(object)"" IL_0007: nop IL_0008: nop IL_0009: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_UsesThis() { var source = @"public record C(int I) { public C(C c) : this(c.I) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(c.I) Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(3, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_DerivesFromObject_UsesBase() { var source = @"public record C(int I) { public C(C c) : base() { System.Console.Write(""RAN ""); } public static void Main() { var c = new C(1); System.Console.Write(c.I); System.Console.Write("" ""); var c2 = c with { I = 2 }; System.Console.Write(c2.I); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "1 RAN 2", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr ""RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_NoPositionalMembers() { var source = @"public record B(object N1, object N2) { } public record C(object P1) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesThis() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) : this(1, 2) // 1 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(1, 2) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(6, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesBase() { var source = @"public record B(int i) { } public record C(int j) : B(0) { public C(C c) : base(1) // 1 { } } #nullable enable public record D(int j) : B(0) { public D(D? d) : base(1) // 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(6, 21), // (13,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public D(D? d) : base(1) // 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(13, 22) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public D(D d) : base(d) { System.Console.Write(""RAN ""); } public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) RAN (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: nop IL_0009: ldstr ""RAN "" IL_000e: call ""void System.Console.Write(string)"" IL_0013: nop IL_0014: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_Synthesized_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: ldfld ""int D.<J>k__BackingField"" IL_000f: stfld ""int D.<J>k__BackingField"" IL_0014: ldarg.0 IL_0015: ldarg.1 IL_0016: ldfld ""int D.field"" IL_001b: stfld ""int D.field"" IL_0020: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButPrivate() { var source = @"public record B(object N1, object N2) { private B(B b) { } } public record C(object P1, object P2) : B(0, 1) { private C(C c) : base(2, 3) { } // 1 } public record D(object P1, object P2) : B(0, 1) { private D(D d) : base(d) { } // 2 } public record E(object P1, object P2) : B(0, 1); // 3 "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,13): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // private B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 13), // (7,13): error CS8878: A copy constructor 'C.C(C)' must be public or protected because the record is not sealed. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "C").WithArguments("C.C(C)").WithLocation(7, 13), // (7,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(7, 22), // (11,13): error CS8878: A copy constructor 'D.D(D)' must be public or protected because the record is not sealed. // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "D").WithArguments("D.D(D)").WithLocation(11, 13), // (11,22): error CS0122: 'B.B(B)' is inaccessible due to its protection level // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(11, 22), // (13,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record E(object P1, object P2) : B(0, 1); // 3 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("B").WithLocation(13, 15) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCaller() { var sourceA = @"public record B(object N1, object N2) { internal B(B b) { } }"; var compA = CreateCompilation(sourceA); compA.VerifyDiagnostics( // (3,14): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // internal B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 14) ); var refA = compA.ToMetadataReference(); var sourceB = @" record C(object P1, object P2) : B(3, 4); // 1 "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (2,8): error CS8867: No accessible copy constructor found in base type 'B'. // record C(object P1, object P2) : B(3, 4); // 1 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 8) ); var sourceC = @" record C(object P1, object P2) : B(3, 4) { protected C(C c) : base(c) { } // 1, 2 } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9); compC.VerifyDiagnostics( // (4,24): error CS0122: 'B.B(B)' is inaccessible due to its protection level // protected C(C c) : base(c) { } // 1, 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(4, 24) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCallerFromPE_WithIVT() { var sourceA = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""AssemblyB"")] internal record B(object N1, object N2) { public B(B b) { } }"; var compA = CreateCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, assemblyName: "AssemblyA", parseOptions: TestOptions.Regular9); var refA = compA.EmitToImageReference(); var sourceB = @" record C(int j) : B(3, 4); "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compB.VerifyDiagnostics(); var sourceC = @" record C(int j) : B(3, 4) { protected C(C c) : base(c) { } } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compC.VerifyDiagnostics(); var compB2 = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB2"); compB2.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C.ToString()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C.GetHashCode()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C.Equals(object?)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,19): error CS0122: 'B' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "B").WithArguments("B").WithLocation(2, 19), // (2,20): error CS0122: 'B.B(object, object)' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "(3, 4)").WithArguments("B.B(object, object)").WithLocation(2, 20) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButPrivate_InSealedType() { var source = @"public record B(int i) { } public sealed record C(int j) : B(0) { private C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var copyCtor = comp.GetMembers("C..ctor")[1]; Assert.Equal("C..ctor(C c)", copyCtor.ToTestDisplayString()); Assert.True(copyCtor.DeclaredAccessibility == Accessibility.Private); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButInternal() { var source = @"public record B(object N1, object N2) { } public sealed record Sealed(object P1, object P2) : B(0, 1) { internal Sealed(Sealed s) : base(s) { } } public record Unsealed(object P1, object P2) : B(0, 1) { internal Unsealed(Unsealed s) : base(s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,14): error CS8878: A copy constructor 'Unsealed.Unsealed(Unsealed)' must be public or protected because the record is not sealed. // internal Unsealed(Unsealed s) : base(s) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Unsealed").WithArguments("Unsealed.Unsealed(Unsealed)").WithLocation(12, 14) ); var sealedCopyCtor = comp.GetMembers("Sealed..ctor")[1]; Assert.Equal("Sealed..ctor(Sealed s)", sealedCopyCtor.ToTestDisplayString()); Assert.True(sealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); var unsealedCopyCtor = comp.GetMembers("Unsealed..ctor")[1]; Assert.Equal("Unsealed..ctor(Unsealed s)", unsealedCopyCtor.ToTestDisplayString()); Assert.True(unsealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind() { var source = @"public record B(int i) { public B(ref B b) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public B(ref B b) => throw null; // 1, not recognized as copy constructor Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "B").WithLocation(3, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind_WithThisInitializer() { var source = @"public record B(int i) { public B(ref B b) : this(0) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 i)", "B..ctor(ref B b)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithPrivateField() { var source = @"public record B(object N1, object N2) { private int field1 = 100; public int GetField1() => field1; } public record C(object P1, object P2) : B(3, 4) { private int field2 = 200; public int GetField2() => field2; static void Main() { var c1 = new C(1, 2); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2, c2.GetField1(), c2.GetField2())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4, 100, 200)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 44 (0x2c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ldarg.0 IL_0020: ldarg.1 IL_0021: ldfld ""int C.field2"" IL_0026: stfld ""int C.field2"" IL_002b: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_MissingInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Removed copy constructor //.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); var source2 = @" public record C : B { public C(C c) { } }"; var comp2 = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics( // (4,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(4, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Inaccessible copy constructor .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata() { // IL for a minimal `public record B { }` with injected copy constructors var ilSource_template = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { INJECT .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void B::.ctor(class B) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { public static void Main() { var c = new C(); _ = c with { }; } }"; // We're going to inject various copy constructors into record B (at INJECT marker), and check which one is used // by derived record C // The RAN and THROW markers are shorthands for method bodies that print "RAN" and throw, respectively. // .ctor(B) vs. .ctor(modopt B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW "); // .ctor(modopt B) alone verify(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN "); // .ctor(B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(modopt B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int32) '' ) cil managed THROW "); // .ctor(modeopt1 B) vs. .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); // private .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt B) verifyBoth(@" .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); void verifyBoth(string inject1, string inject2, bool isError = false) { verify(inject1 + inject2, isError); verify(inject2 + inject1, isError); } void verify(string inject, bool isError = false) { var ranBody = @" { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } "; var throwBody = @" { IL_0000: ldnull IL_0001: throw } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource_template.Replace("INJECT", inject).Replace("RAN", ranBody).Replace("THROW", throwBody), parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var expectedDiagnostics = isError ? new[] { // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) } : new DiagnosticDescription[] { }; comp.VerifyDiagnostics(expectedDiagnostics); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } } } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata_GenericType() { // IL for a minimal `public record B<T> { }` with modopt in nested position of parameter type var ilSource = @" .class public auto ansi beforefieldinit B`1<T> extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class B`1<!T>> { .method family hidebysig specialname rtspecialname instance void .ctor ( class B`1<!T modopt(int64)> '' ) cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig specialname newslot virtual instance class B`1<!T> '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void class B`1<!T>::.ctor(class B`1<!0>) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B`1<!T> '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B`1::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C<T> : B<T> { } public class Program { public static void Main() { var c = new C<string>(); _ = c with { }; } }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void CopyCtor_Accessibility_01(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,6): error CS8878: A copy constructor 'A.A(A)' must be public or protected because the record is not sealed. // A(A a) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); } [Theory] [InlineData("public")] [InlineData("protected")] public void CopyCtor_Accessibility_02(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("public")] public void CopyCtor_Accessibility_03(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("private protected")] [InlineData("internal protected")] [InlineData("protected")] public void CopyCtor_Accessibility_04(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics( // (4,15): warning CS0628: 'A.A(A)': new protected member declared in sealed type // protected A(A a) Diagnostic(ErrorCode.WRN_ProtectedInSealed, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void CopyCtor_Signature_01() { var source = @" record A(int X) { public A(in A a) : this(-15) => System.Console.Write(""RAN""); public static void Main() { var a = new A(123); System.Console.Write((a with { }).X); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "123").VerifyDiagnostics(); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record B(int X) { public int Y { get; init; } public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record B(int X, int Y); record C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""B C.B.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int C.Z.get"" IL_000f: stind.i4 IL_0010: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_02() { var source = @" record B { public int X(int y) => y; } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_03() { var source = @" using System; record B { public int X() => 3; } record C(int X, int Y) : B { public new int X { get; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "02"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_04() { var source = @" record C(int X, int Y) { public int X(int arg) => 3; static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'C' already contains a definition for 'X' // public int X(int arg) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(4, 16) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record C(int X) { int X; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(4, 10), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_EventCollision() { var source = @" using System; record C(Action X) { event Action X; static void M(C c) { switch (c) { case C(Action x): Console.Write(x); break; } } static void Main() { M(new C(() => { })); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0102: The type 'C' already contains a definition for 'X' // event Action X; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(6, 18), // (6,18): warning CS0067: The event 'C.X' is never used // event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(6, 18) ); Assert.Equal( "void C.Deconstruct(out System.Action X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_WriteOnlyPropertyInBase() { var source = @" using System; record B { public int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(9, 14), // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14)); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_PrivateWriteOnlyPropertyInBase() { var source = @" using System; record B { private int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Inheritance_01() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Null(comp.GetMember("C.Deconstruct")); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_02() { var source = @" using System; record B(int X, int Y) { // https://github.com/dotnet/roslyn/issues/44902 internal B() : this(0, 1) { } } record C(int X, int Y, int Z) : B(X, Y) { static void M(C c) { switch (c) { case C(int x, int y, int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "01201"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y, out System.Int32 Z)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_03() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14), // (9,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 21) ); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_04() { var source = @" using System; record A<T>(T P) { internal A() : this(default(T)) { } } record B1(int P, object Q) : A<int>(P) { internal B1() : this(0, null) { } } record B2(object P, object Q) : A<object>(P) { internal B2() : this(null, null) { } } record B3<T>(T P, object Q) : A<T>(P) { internal B3() : this(default, 0) { } } class C { static void M0(A<int> arg) { switch (arg) { case A<int>(int x): Console.Write(x); break; } } static void M1(B1 arg) { switch (arg) { case B1(int p, object q): Console.Write(p); Console.Write(q); break; } } static void M2(B2 arg) { switch (arg) { case B2(object p, object q): Console.Write(p); Console.Write(q); break; } } static void M3(B3<int> arg) { switch (arg) { case B3<int>(int p, object q): Console.Write(p); Console.Write(q); break; } } static void Main() { M0(new A<int>(0)); M1(new B1(1, 2)); M2(new B2(3, 4)); M3(new B3<int>(5, 6)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123456"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void A<T>.Deconstruct(out T P)", comp.GetMember("A.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B1.Deconstruct(out System.Int32 P, out System.Object Q)", comp.GetMember("B1.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B2.Deconstruct(out System.Object P, out System.Object Q)", comp.GetMember("B2.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B3<T>.Deconstruct(out T P, out System.Object Q)", comp.GetMember("B3.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_01() { var source = @" using System; record C(int X, int Y) { public long X { get; init; } public long Y { get; init; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,14): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "int", "X").WithLocation(4, 14), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (4,21): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 18), // (5,28): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 28) ); Assert.Equal( "void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_03() { var source = @" using System; class Base { } class Derived : Base { } record C(Derived X, Base Y) { public Base X { get; init; } public Derived Y { get; init; } static void M(C c) { switch (c) { case C(Derived x, Base y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(new Derived(), new Base())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'Derived' to match positional parameter 'X'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "Derived", "X").WithLocation(7, 18), // (7,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 18), // (7,26): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'Base' to match positional parameter 'Y'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "Base", "Y").WithLocation(7, 26), // (7,26): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 26)); Assert.Equal( "void C.Deconstruct(out Derived X, out Base Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record C() { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_02() { var source = @"using System; record C() { public void Deconstruct(out int X, out int Y) { X = 1; Y = 2; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_03() { var source = @"using System; record C() { private void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_04() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public static void Deconstruct() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0176: Member 'C.Deconstruct()' cannot be accessed with an instance reference; qualify it with a type name instead // case C(): Diagnostic(ErrorCode.ERR_ObjectProhibited, "()", isSuppressed: false).WithArguments("C.Deconstruct()").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_05() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public int Deconstruct() { return 1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_01() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int Z) { Z = X + Y; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } switch (b) { case B(int z): Console.Write(z); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", "void B.Deconstruct(out System.Int32 Z)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_03() { var source = @"using System; record B(int X) { public void Deconstruct(int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X)", "void B.Deconstruct(System.Int32 X)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_04() { var source = @"using System; record B(int X) { public void Deconstruct(ref int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0663: 'B' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public void Deconstruct(ref int X) Diagnostic(ErrorCode.ERR_OverloadRefKind, "Deconstruct").WithArguments("B", "method", "ref", "out").WithLocation(5, 17) ); Assert.Equal(2, comp.GetMembers("B.Deconstruct").Length); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_05() { var source = @"using System; record A(int X) { public A() : this(0) { } public int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_06() { var source = @"using System; record A(int X) { public A() : this(0) { } public virtual int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void Deconstruct_Shadowing_01() { var source = @" abstract record A(int X) { public abstract int Deconstruct(out int a, out int b); } abstract record B(int X, int Y) : A(X) { public static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): error CS0533: 'B.Deconstruct(out int, out int)' hides inherited abstract member 'A.Deconstruct(out int, out int)' // abstract record B(int X, int Y) : A(X) Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Deconstruct(out int, out int)", "A.Deconstruct(out int, out int)").WithLocation(6, 17) ); } [Fact] public void Deconstruct_TypeMismatch_01() { var source = @" record A(int X) { public System.Type X => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14) ); } [Fact] public void Deconstruct_TypeMismatch_02() { var source = @" record A { public System.Type X => throw null; } record B(int X) : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (7,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record B(int X) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45010")] [WorkItem(45010, "https://github.com/dotnet/roslyn/issues/45010")] public void Deconstruct_ObsoleteProperty() { var source = @"using System; record B(int X) { [Obsolete] int X { get; } = X; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45009")] [WorkItem(45009, "https://github.com/dotnet/roslyn/issues/45009")] public void Deconstruct_RefProperty() { var source = @"using System; record B(int X) { static int _x = 2; ref int X => ref _x; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "2"); verifier.VerifyDiagnostics(); var deconstruct = verifier.Compilation.GetMember("B.Deconstruct"); Assert.Equal("void B.Deconstruct(out System.Int32 X)", deconstruct.ToTestDisplayString(includeNonNullable: false)); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); Assert.False(deconstruct.IsAbstract); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsOverride); Assert.False(deconstruct.IsSealed); Assert.True(deconstruct.IsImplicitlyDeclared); } [Fact] public void Deconstruct_Static() { var source = @" using System; record B(int X, int Y) { static int Y { get; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData(false)] [InlineData(true)] public void Overrides_01(bool usePreview) { var source = @"record A { public sealed override bool Equals(object other) => false; public sealed override int GetHashCode() => 0; public sealed override string ToString() => null; } record B(int X, int Y) : A { }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyDiagnostics( // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } else { comp.VerifyDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (5,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(5, 35), // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", "A B." + WellKnownMemberNames.CloneMethodName + "()", "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Overrides_02() { var source = @"abstract record A { public abstract override bool Equals(object other); public abstract override int GetHashCode(); public abstract override string ToString(); } record B(int X, int Y) : A { }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (3,35): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public abstract override bool Equals(object other); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 35), // (7,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(object)' // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(object)").WithLocation(7, 8) ); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ObjectEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public final hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.Equals(object?)' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.Equals(object?)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance int32 Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(object?)': return type must be 'int' to match overridden member 'A.Equals(object)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(object?)", "A.Equals(object)", "int").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_05() { var source0 = @"namespace System { public class Object { public virtual int Equals(object other) => default; public virtual int GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.Equals(object?)': return type must be 'int' to match overridden member 'object.Equals(object)' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.Equals(object?)", "object.Equals(object)", "int").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectEquals_06() { var source = @"record A { public static new bool Equals(object obj) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 28) ); } [Fact] public void ObjectGetHashCode_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var source2 = @" public record B : A { public override int GetHashCode() => 0; }"; var source3 = @" public record C : B { } "; var source4 = @" public record C : B { public override int GetHashCode() => 0; } "; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source1 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source1 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source2 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance bool GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_04() { var source = @"record A { public override bool GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,26): error CS0508: 'A.GetHashCode()': return type must be 'int' to match overridden member 'object.GetHashCode()' // public override bool GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("A.GetHashCode()", "object.GetHashCode()", "int").WithLocation(3, 26) ); } [Fact] public void ObjectGetHashCode_05() { var source = @"record A { public new int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_06() { var source = @"record A { public static new int GetHashCode() => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,27): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public static new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 27), // (6,8): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(6, 8) ); } [Fact] public void ObjectGetHashCode_07() { var source = @"record A { public new int GetHashCode => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS0102: The type 'A' already contains a definition for 'GetHashCode' // public new int GetHashCode => throw null; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "GetHashCode").WithArguments("A", "GetHashCode").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_08() { var source = @"record A { public new void GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,21): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new void GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 21) ); } [Fact] public void ObjectGetHashCode_09() { var source = @"record A { public void GetHashCode(int x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); Assert.Equal("System.Int32 A.GetHashCode()", comp.GetMembers("A.GetHashCode").First().ToTestDisplayString()); } [Fact] public void ObjectGetHashCode_10() { var source = @" record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32) ); } [Fact] public void ObjectGetHashCode_11() { var source = @" sealed record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void ObjectGetHashCode_12() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public final hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_13() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override A GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override A GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override B GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8830: 'B.GetHashCode()': Target runtime doesn't support covariant return types in overrides. Return type must be 'A' to match overridden member 'A.GetHashCode()' // public override B GetHashCode() => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "A").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_15() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual Something GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } public class Something { } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override Something GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,31): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override Something GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 31), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_16() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override bool GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,26): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override bool GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 26), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_17() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.GetHashCode()': return type must be 'bool' to match overridden member 'object.GetHashCode()' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.GetHashCode()", "object.GetHashCode()", "bool").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void BaseEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance int32 Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(A?)': return type must be 'int' to match overridden member 'A.Equals(A)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(A?)", "A.Equals(A)", "int").WithLocation(2, 15) ); } [Fact] public void BaseEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.Equals(B?)' does not override expected method from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.Equals(B?)", "B").WithLocation(2, 15) ); } [Fact] public void BaseEquals_05() { var source = @" record A { } record B : A { public override bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,26): error CS0111: Type 'B' already defines a member called 'Equals' with the same parameter types // public override bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "B").WithLocation(8, 26) ); } [Fact] public void RecordEquals_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(A x); } record B : A { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (5,26): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public abstract bool Equals(A x); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 26), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); } [Fact] public void RecordEquals_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,26): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 26) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,33): error CS8872: 'B.Equals(B)' must allow overriding because the containing record is not sealed. // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("B.Equals(B)").WithLocation(9, 33), // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); } [Fact] public void RecordEquals_04() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } sealed record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); var copyCtor = comp.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Protected, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); copyCtor = comp.GetMember<NamedTypeSymbol>("B").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Private, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); } [Fact] public void RecordEquals_05() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } abstract record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,17): error CS0533: 'B.Equals(B?)' hides inherited abstract member 'A.Equals(B)' // abstract record B : A Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Equals(B?)", "A.Equals(B)").WithLocation(7, 17) ); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_06(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } " + modifiers + @" record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (8,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(B)' // record B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(B)").WithLocation(8, 8) ); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_07(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_08(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(C x); } abstract record B : A { public override bool Equals(C x) => Report(""B.Equals(C)""); } " + modifiers + @" record C : B { } class Program { static void Main() { A a1 = new C(); C c2 = new C(); System.Console.WriteLine(a1.Equals(c2)); System.Console.WriteLine(c2.Equals(a1)); System.Console.WriteLine(c2.Equals((C)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(C) False True True ").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_09(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void RecordEquals_11(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.Equals(A)': virtual or abstract members cannot be private // virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_VirtualPrivate, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B other) => Report(""A.Equals(B)""); } class B { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a1.Equals((object)a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record A { public virtual int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,24): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_14() { var source = @" record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (4,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public virtual bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 20), // (4,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 25) ); } [Fact] public void RecordEquals_15() { var source = @" record A { public virtual Boolean Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,20): error CS0246: The type or namespace name 'Boolean' could not be found (are you missing a using directive or an assembly reference?) // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Boolean").WithArguments("Boolean").WithLocation(4, 20), // (4,28): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 28) ); } [Fact] public void RecordEquals_16() { var source = @" abstract record A { } record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_17() { var source = @" abstract record A { } sealed record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_18() { var source = @" sealed record A { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_19() { var source = @" record A { public static bool Equals(A x) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24), // (7,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(7, 8) ); } [Fact] public void RecordEquals_20() { var source = @" sealed record A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // sealed record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityContract_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Fact] public void EqualityContract_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(9, 43) ); } [Fact] public void EqualityContract_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } sealed record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void EqualityContract_04(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected virtual System.Type EqualityContract { get { Report(""A.EqualityContract""); return typeof(B); } } } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True True ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); } [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void EqualityContract_05(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void EqualityContract_06(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.EqualityContract': virtual or abstract members cannot be private // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_VirtualPrivate, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length), // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_07(string modifiers) { var source = @" record A { } " + modifiers + @" record B : A { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_08(string modifiers) { var source = modifiers + @" record B { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { B a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContractGet.IsVirtual); Assert.False(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Fact] public void EqualityContract_09() { var source = @" record A { protected virtual int EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27) ); } [Fact] public void EqualityContract_10() { var source = @" record A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(WellKnownType.System_Type); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8) ); } [Fact] public void EqualityContract_11() { var source = @" record A { protected virtual Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(4, 23) ); } [Fact] public void EqualityContract_12() { var source = @" record A { protected System.Type EqualityContract => throw null; } sealed record B { protected System.Type EqualityContract => throw null; } sealed record C { protected virtual System.Type EqualityContract => throw null; } record D { protected virtual System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 27), // (10,27): warning CS0628: 'B.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (10,27): error CS8879: Record member 'B.EqualityContract' must be private. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (11,12): warning CS0628: 'B.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("B.EqualityContract.get").WithLocation(11, 12), // (16,35): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (16,35): error CS8879: Record member 'C.EqualityContract' must be private. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (17,12): error CS0549: 'C.EqualityContract.get' is a new virtual member in sealed type 'C' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("C.EqualityContract.get", "C").WithLocation(17, 12) ); } [Fact] public void EqualityContract_13() { var source = @" record A {} record B : A { protected System.Type EqualityContract => throw null; } sealed record C : A { protected System.Type EqualityContract => throw null; } sealed record D : A { protected virtual System.Type EqualityContract => throw null; } record E : A { protected virtual System.Type EqualityContract => throw null; } record F : A { protected override System.Type EqualityContract => throw null; } record G : A { protected sealed override System.Type EqualityContract => throw null; } sealed record H : A { protected sealed override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,27): error CS8876: 'B.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("B.EqualityContract", "A").WithLocation(7, 27), // (7,27): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(7, 27), // (7,27): warning CS0114: 'B.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 27), // (13,27): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(13, 27), // (13,27): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(13, 27), // (13,27): warning CS0114: 'C.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract").WithLocation(13, 27), // (14,12): warning CS0628: 'C.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("C.EqualityContract.get").WithLocation(14, 12), // (19,35): warning CS0628: 'D.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("D.EqualityContract").WithLocation(19, 35), // (19,35): error CS8876: 'D.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "A").WithLocation(19, 35), // (19,35): warning CS0114: 'D.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("D.EqualityContract", "A.EqualityContract").WithLocation(19, 35), // (20,12): error CS0549: 'D.EqualityContract.get' is a new virtual member in sealed type 'D' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("D.EqualityContract.get", "D").WithLocation(20, 12), // (25,35): error CS8876: 'E.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("E.EqualityContract", "A").WithLocation(25, 35), // (25,35): warning CS0114: 'E.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("E.EqualityContract", "A.EqualityContract").WithLocation(25, 35), // (37,43): error CS8872: 'G.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("G.EqualityContract").WithLocation(37, 43) ); } [Fact] public void EqualityContract_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_15() { var source = @" record A { protected virtual int EqualityContract => throw null; } record B : A { } record C : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27), // (8,8): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // record B : A Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(8, 8), // (14,36): error CS1715: 'C.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract", "int").WithLocation(14, 36) ); } [Fact] public void EqualityContract_16() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot final virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_17() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { protected virtual System.Type EqualityContract => throw null; } public record D : A { protected virtual int EqualityContract => throw null; } public record E : A { protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.EqualityContract': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(2, 15), // (6,35): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 35), // (11,27): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 27), // (16,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 23), // (21,36): error CS0115: 'F.EqualityContract': no suitable method found to override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_OverrideNotExpected, "EqualityContract").WithArguments("F.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_18() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { } public record D : B { new protected virtual System.Type EqualityContract => throw null; } public record E : B { new protected virtual int EqualityContract => throw null; } public record F : B { new protected virtual Type EqualityContract => throw null; } public record G : B { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8876: 'C.EqualityContract' does not override expected property from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "C").WithArguments("C.EqualityContract", "B").WithLocation(2, 15), // (6,39): error CS8876: 'D.EqualityContract' does not override expected property from 'B'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "B").WithLocation(6, 39), // (11,31): error CS8874: Record member 'E.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("E.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS8876: 'G.EqualityContract' does not override expected property from 'B'. // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("G.EqualityContract", "B").WithLocation(21, 36) ); } [Fact] public void EqualityContract_19() { var source = @"sealed record A { protected static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,34): warning CS0628: 'A.EqualityContract': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8879: Record member 'A.EqualityContract' must be private. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8877: Record member 'A.EqualityContract' may not be static. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,54): warning CS0628: 'A.EqualityContract.get': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("A.EqualityContract.get").WithLocation(3, 54) ); } [Fact] public void EqualityContract_20() { var source = @"sealed record A { private static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,32): error CS8877: Record member 'A.EqualityContract' may not be static. // private static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 32) ); } [Fact] public void EqualityContract_21() { var source = @" sealed record A { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("A.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type A.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Private, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_22() { var source = @" record A; sealed record B : A { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_23() { var source = @" record A { protected static System.Type EqualityContract => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,34): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 34), // (7,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 8) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_SetterOnlyProperty() { var src = @" record R { protected virtual System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected virtual System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(4, 35) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_GetterAndSetterProperty() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R; "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_25_SetterOnlyProperty_DerivedRecord() { var src = @" record Base; record R : Base { protected override System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(5, 36), // (5,55): error CS0546: 'R.EqualityContract.set': cannot override because 'Base.EqualityContract' does not have an overridable set accessor // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("R.EqualityContract.set", "Base.EqualityContract").WithLocation(5, 55) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_26_SetterOnlyProperty_InMetadata() { // `record Base;` with modified EqualityContract property, method bodies simplified and nullability removed var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool PrintMembers( class [mscorlib] System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals( class Base other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance class Base '<Clone>$'() cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname newslot virtual instance void set_EqualityContract ( class [mscorlib]System.Type 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } // Property has a setter but no getter .property instance class [mscorlib]System.Type EqualityContract() { .set instance void Base::set_EqualityContract(class [mscorlib]System.Type) } } "; var src = @" record R : Base; "; var comp = CreateCompilationWithIL(src, il); comp.VerifyEmitDiagnostics( // (2,8): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // record R : Base; Diagnostic(ErrorCode.ERR_NoGetToOverride, "R").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(2, 8) ); var src2 = @" record R : Base { protected override System.Type EqualityContract => typeof(R); } "; var comp2 = CreateCompilationWithIL(src2, il); comp2.VerifyEmitDiagnostics( // (4,56): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // protected override System.Type EqualityContract => typeof(R); Diagnostic(ErrorCode.ERR_NoGetToOverride, "typeof(R)").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(4, 56) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_27_GetterAndSetterProperty_ExplicitlyOverridden() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R { protected override System.Type EqualityContract { get { System.Console.Write(""RAN2 ""); return GetType(); } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN RAN2"); } [Fact] public void EqualityOperators_01() { var source = @" record A(int X) { public virtual bool Equals(ref A other) => throw null; static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); Test(new A(4), new B(4, 5)); Test(new B(6, 7), new B(6, 7)); Test(new B(8, 9), new B(8, 10)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } record B(int X, int Y) : A(X); "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False False False True True True True False False False False True True False False True True True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_02() { var source = @" record B; record A(int X) : B { public virtual bool Equals(A other) { System.Console.WriteLine(""Equals(A other)""); return base.Equals(other) && X == other.X; } static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); Test(new A(3), new B()); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } static void Test(A a1, B b2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == b2, b2 == a1, a1 != b2, b2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False Equals(A other) Equals(A other) False False True True Equals(A other) Equals(A other) Equals(A other) Equals(A other) True True False False Equals(A other) Equals(A other) Equals(A other) Equals(A other) False False True True True True False False Equals(A other) Equals(A other) False False True True ").VerifyDiagnostics( // (6,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(6, 25) ); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_08() { var source = @" record A { public virtual string Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0738: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement 'IEquatable<A>.Equals(A)' because it does not have the matching return type of 'bool'. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)", "bool").WithLocation(2, 8), // (4,27): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual string Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 27), // (4,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual string Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 27) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record A(int X) { } "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False False False True True True True False False False False True True ").VerifyDiagnostics(); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_01() { var src = @"record C(object Q) { public object P { get; } public object P { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'C' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.Q { get; init; }", "System.Object C.P { get; }", "System.Object C.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_02() { var src = @"record C(object P, object Q) { public object P { get; } public int P { get; } public int Q { get; } public object Q { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): error CS8866: Record member 'C.Q' must be a readable instance property or field of type 'object' to match positional parameter 'Q'. // record C(object P, object Q) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Q").WithArguments("C.Q", "object", "Q").WithLocation(1, 27), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (4,16): error CS0102: The type 'C' already contains a definition for 'P' // public int P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 16), // (6,19): error CS0102: The type 'C' already contains a definition for 'Q' // public object Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; }", "System.Int32 C.P { get; }", "System.Int32 C.Q { get; }", "System.Object C.Q { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void DuplicateProperty_03() { var src = @"record A { public object P { get; } public object P { get; } public object Q { get; } public int Q { get; } } record B(object Q) : A { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'A' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("A", "P").WithLocation(4, 19), // (6,16): error CS0102: The type 'A' already contains a definition for 'Q' // public int Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("A", "Q").WithLocation(6, 16), // (8,17): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(8, 17)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void NominalRecordWith() { var src = @" using System; record C { public int X { get; init; } public string Y; public int Z { get; set; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3 }; var c2 = new C() { X = 1, Y = ""2"", Z = 3 }; Console.WriteLine(c.Equals(c2)); var c3 = c2 with { X = 3, Y = ""2"", Z = 1 }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c3.Equals(c2)); Console.WriteLine(c2.X + "" "" + c2.Y + "" "" + c2.Z); } }"; CompileAndVerify(src, expectedOutput: @" True True False 1 2 3").VerifyDiagnostics(); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = c with { X = 2 }; Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = d with { X = 2, Y = 3 }; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); C c3 = d; C c4 = d2; c3 = c3 with { X = 3 }; c4 = c4 with { X = 4 }; d = (D)c3; d2 = (D)c4; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } }"; var verifier = CompileAndVerify(src2, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3 3 2 4 3").VerifyDiagnostics(); verifier.VerifyIL("E.Main", @" { // Code size 318 (0x13e) .maxstack 3 .locals init (C V_0, //c D V_1, //d D V_2, //d2 C V_3, //c3 C V_4, //c4 int V_5) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.X.init"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldc.i4.2 IL_0015: callvirt ""void C.X.init"" IL_001a: ldloc.0 IL_001b: callvirt ""int C.X.get"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: callvirt ""int C.X.get"" IL_002a: call ""void System.Console.WriteLine(int)"" IL_002f: ldc.i4.2 IL_0030: newobj ""D..ctor(int)"" IL_0035: dup IL_0036: ldc.i4.1 IL_0037: callvirt ""void C.X.init"" IL_003c: stloc.1 IL_003d: ldloc.1 IL_003e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0043: castclass ""D"" IL_0048: dup IL_0049: ldc.i4.2 IL_004a: callvirt ""void C.X.init"" IL_004f: dup IL_0050: ldc.i4.3 IL_0051: callvirt ""void D.Y.init"" IL_0056: stloc.2 IL_0057: ldloc.1 IL_0058: callvirt ""int C.X.get"" IL_005d: stloc.s V_5 IL_005f: ldloca.s V_5 IL_0061: call ""string int.ToString()"" IL_0066: ldstr "" "" IL_006b: ldloc.1 IL_006c: callvirt ""int D.Y.get"" IL_0071: stloc.s V_5 IL_0073: ldloca.s V_5 IL_0075: call ""string int.ToString()"" IL_007a: call ""string string.Concat(string, string, string)"" IL_007f: call ""void System.Console.WriteLine(string)"" IL_0084: ldloc.2 IL_0085: callvirt ""int C.X.get"" IL_008a: stloc.s V_5 IL_008c: ldloca.s V_5 IL_008e: call ""string int.ToString()"" IL_0093: ldstr "" "" IL_0098: ldloc.2 IL_0099: callvirt ""int D.Y.get"" IL_009e: stloc.s V_5 IL_00a0: ldloca.s V_5 IL_00a2: call ""string int.ToString()"" IL_00a7: call ""string string.Concat(string, string, string)"" IL_00ac: call ""void System.Console.WriteLine(string)"" IL_00b1: ldloc.1 IL_00b2: stloc.3 IL_00b3: ldloc.2 IL_00b4: stloc.s V_4 IL_00b6: ldloc.3 IL_00b7: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00bc: dup IL_00bd: ldc.i4.3 IL_00be: callvirt ""void C.X.init"" IL_00c3: stloc.3 IL_00c4: ldloc.s V_4 IL_00c6: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00cb: dup IL_00cc: ldc.i4.4 IL_00cd: callvirt ""void C.X.init"" IL_00d2: stloc.s V_4 IL_00d4: ldloc.3 IL_00d5: castclass ""D"" IL_00da: stloc.1 IL_00db: ldloc.s V_4 IL_00dd: castclass ""D"" IL_00e2: stloc.2 IL_00e3: ldloc.1 IL_00e4: callvirt ""int C.X.get"" IL_00e9: stloc.s V_5 IL_00eb: ldloca.s V_5 IL_00ed: call ""string int.ToString()"" IL_00f2: ldstr "" "" IL_00f7: ldloc.1 IL_00f8: callvirt ""int D.Y.get"" IL_00fd: stloc.s V_5 IL_00ff: ldloca.s V_5 IL_0101: call ""string int.ToString()"" IL_0106: call ""string string.Concat(string, string, string)"" IL_010b: call ""void System.Console.WriteLine(string)"" IL_0110: ldloc.2 IL_0111: callvirt ""int C.X.get"" IL_0116: stloc.s V_5 IL_0118: ldloca.s V_5 IL_011a: call ""string int.ToString()"" IL_011f: ldstr "" "" IL_0124: ldloc.2 IL_0125: callvirt ""int D.Y.get"" IL_012a: stloc.s V_5 IL_012c: ldloca.s V_5 IL_012e: call ""string int.ToString()"" IL_0133: call ""string string.Concat(string, string, string)"" IL_0138: call ""void System.Console.WriteLine(string)"" IL_013d: ret }"); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference_WithCovariantReturns(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? src : new[] { src, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = CHelper(c); Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = DHelper(d); Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } private static C CHelper(C c) { return c with { X = 2 }; } private static D DHelper(D d) { return d with { X = 2, Y = 3 }; } }"; var verifier = CompileAndVerify(RuntimeUtilities.IsCoreClrRuntime ? src2 : new[] { src2, IsExternalInitTypeDefinition }, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3", targetFramework: TargetFramework.StandardLatest).VerifyDiagnostics().VerifyIL("E.CHelper", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: ret } "); if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL("E.DHelper", @" { // Code size 21 (0x15) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""D D.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: dup IL_000e: ldc.i4.3 IL_000f: callvirt ""void D.Y.init"" IL_0014: ret } "); } else { verifier.VerifyIL("E.DHelper", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: castclass ""D"" IL_000b: dup IL_000c: ldc.i4.2 IL_000d: callvirt ""void C.X.init"" IL_0012: dup IL_0013: ldc.i4.3 IL_0014: callvirt ""void D.Y.init"" IL_0019: ret } "); } } private static ImmutableArray<Symbol> GetProperties(CSharpCompilation comp, string typeName) { return comp.GetMember<NamedTypeSymbol>(typeName).GetMembers().WhereAsArray(m => m.Kind == SymbolKind.Property); } [Fact] public void BaseArguments_01() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X, int Y = 123) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } C(int X, int Y, int Z = 124) : this(X, Y) {} }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal(Accessibility.Public, symbol.ContainingSymbol.DeclaredAccessibility); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(X, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); #nullable disable var operation = model.GetOperation(baseWithargs); VerifyOperationTree(comp, operation, @" IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Null(model.GetOperation(baseWithargs.Type)); Assert.Null(model.GetOperation(baseWithargs.Parent)); Assert.Same(operation.Parent.Parent, model.GetOperation(baseWithargs.Parent.Parent)); Assert.Equal(SyntaxKind.RecordDeclaration, baseWithargs.Parent.Parent.Kind()); VerifyOperationTree(comp, operation.Parent.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'record C(in ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'record C(in ... }') ExpressionBody: null "); Assert.Null(operation.Parent.Parent.Parent); VerifyFlowGraph(comp, operation.Parent.Parent.Syntax, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); Assert.Equal("= 123", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Y = 123]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 123') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123') "); #nullable enable } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y)", baseWithargs.ToString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); model.VerifyOperationTree(baseWithargs, @" IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last(); Assert.Equal("= 124", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Z = 124]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 124') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 124) (Syntax: '124') "); model.VerifyOperationTree(baseWithargs.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'C(int X, in ... is(X, Y) {}') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(X, Y)') Expression: IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{}') ExpressionBody: null "); } } [Fact] public void BaseArguments_02() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { public static void Main() { var c = new C(1); } private static int Test(int x, out int y) { y = 2; return x; } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var yDecl = OutVarTests.GetOutVarDeclaration(tree, "y"); var yRef = OutVarTests.GetReferences(tree, "y").ToArray(); Assert.Equal(2, yRef.Length); OutVarTests.VerifyModelForOutVar(model, yDecl, yRef[0]); OutVarTests.VerifyNotAnOutLocal(model, yRef[1]); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Test(X, out var y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var y = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "y").First(); Assert.Equal("y", y.Parent!.ToString()); Assert.Equal("(Test(X, out var y), y)", y.Parent!.Parent!.ToString()); Assert.Equal("Base(Test(X, out var y), y)", y.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(y).Symbol; Assert.Equal(SymbolKind.Local, symbol!.Kind); Assert.Equal("System.Int32 y", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "y")); Assert.Contains("y", model.LookupNames(x.SpanStart)); var test = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").First(); Assert.Equal("(Test(X, out var y), y)", test.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(test).Symbol; Assert.Equal(SymbolKind.Method, symbol!.Kind); Assert.Equal("System.Int32 C.Test(System.Int32 x, out System.Int32 y)", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "Test")); Assert.Contains("Test", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_03() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,16): error CS8861: Unexpected argument list. // record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_04() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_05() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24), // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); foreach (var x in xs) { Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_06() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[0], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_07() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C(int X, int Y) : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[1], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); } [Fact] public void BaseArguments_08() { var src = @" record Base { public Base(int Y) { } public Base() {} } record C(int X) : Base(Y) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Y' // record C(int X) : Base(Y) Diagnostic(ErrorCode.ERR_ObjectRequired, "Y").WithArguments("C.Y").WithLocation(11, 24) ); } [Fact] public void BaseArguments_09() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X) : Base(this.X) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0027: Keyword 'this' is not available in the current context // record C(int X) : Base(this.X) Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 24) ); } [Fact] public void BaseArguments_10() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(dynamic X) : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,27): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. // record C(dynamic X) : Base(X) Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "(X)").WithLocation(11, 27) ); } [Fact] public void BaseArguments_11() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { int Z = y; private static int Test(int x, out int y) { y = 2; return x; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0103: The name 'y' does not exist in the current context // int Z = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(13, 13) ); } [Fact] public void BaseArguments_12() { var src = @" using System; class Base { public Base(int X) { } } class C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,7): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Base.Base(int)' // class C : Base(X) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("X", "Base.Base(int)").WithLocation(11, 7), // (11,15): error CS8861: Unexpected argument list. // class C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(11, 15) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_13() { var src = @" using System; interface Base { } struct C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,16): error CS8861: Unexpected argument list. // struct C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_14() { var src = @" using System; interface Base { } interface C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,19): error CS8861: Unexpected argument list. // interface C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_15() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } partial record C { } partial record C(int X, int Y) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } } partial record C { } "; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_16() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => X) { public static void Main() { var c = new C(1); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"1").VerifyDiagnostics(); } [Fact] public void BaseArguments_17() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X, out var y), Test(X, out var z)) { int Z = z; private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,28): 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 // : Base(Test(X, out var y), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(12, 28), // (15,13): error CS0103: The name 'z' does not exist in the current context // int Z = z; Diagnostic(ErrorCode.ERR_NameNotInContext, "z").WithArguments("z").WithLocation(15, 13) ); } [Fact] public void BaseArguments_18() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X + 1, out var z), Test(X + 2, out var z)) { private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,32): error CS0128: A local variable or function named 'z' is already defined in this scope // Test(X + 2, out var z)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(13, 32) ); } [Fact] public void BaseArguments_19() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : this(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,30): error CS1729: 'Base' does not contain a constructor that takes 2 arguments // record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(GetInt(X, out var xx) + xx, Y)").WithArguments("Base", "2").WithLocation(11, 30), // (13,30): error CS1729: 'C' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : this(X, Y, Z, 1) {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "this").WithArguments("C", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(Base original)", "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); SemanticModel speculativeModel; speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); var xxDecl = OutVarTests.GetOutVarDeclaration(speculativePrimaryInitializer.SyntaxTree, "xx"); var xxRef = OutVarTests.GetReferences(speculativePrimaryInitializer.SyntaxTree, "xx").ToArray(); Assert.Equal(1, xxRef.Length); OutVarTests.VerifyModelForOutVar(speculativeModel, xxDecl, xxRef); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", "C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void BaseArguments_20() { var src = @" class Base { public Base(int X) { } public Base() {} } class C : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,15): error CS8861: Unexpected argument list. // class C : Base(GetInt(X, out var xx) + xx, Y), I Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(GetInt(X, out var xx) + xx, Y)").WithLocation(11, 15), // (13,30): error CS1729: 'Base' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("Base", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": base(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void Equality_02() { var source = @"using static System.Console; record C; class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(y) && x.GetHashCode() == y.GetHashCode()); WriteLine(((object)x).Equals(y)); WriteLine(((System.IEquatable<C>)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var ordinaryMethods = comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(6, ordinaryMethods.Length); foreach (var m in ordinaryMethods) { Assert.True(m.IsImplicitlyDeclared); } var verifier = CompileAndVerify(comp, expectedOutput: @"True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(object)", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); } [Fact] public void Equality_03() { var source = @"using static System.Console; record C { private static int _nextId = 0; private int _id; public C() { _id = _nextId++; } } class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(x)); WriteLine(x.Equals(y)); WriteLine(y.Equals(y)); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C._id"" IL_0025: ldarg.1 IL_0026: ldfld ""int C._id"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C._id"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0026: add IL_0027: ret }"); var clone = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void Equality_04() { var source = @"using static System.Console; record A; record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } class Program { static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(new A().Equals(NewB1(1))); WriteLine(NewB1(1).Equals(new A())); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(new A().Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(new A())); WriteLine(((A)NewB2(1)).Equals(NewB2(1)) && ((A)NewB2(1)).GetHashCode() == NewB2(1).GetHashCode()); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False False False False False True True").VerifyDiagnostics( // (3,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(3, 15), // (8,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(8, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B1.<P>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B1.<P>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int B1.<P>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_05() { var source = @"using static System.Console; record A(int P) { internal A() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead } class Program { static A NewA(int p) => new A { P = p }; // Use record base call syntax instead static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(NewA(1).Equals(NewA(2))); WriteLine(NewA(1).Equals(NewA(1)) && NewA(1).GetHashCode() == NewA(1).GetHashCode()); WriteLine(NewA(1).Equals(NewB1(1))); WriteLine(NewB1(1).Equals(NewA(1))); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(NewA(1).Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(NewA(1))); WriteLine(((A)NewB2(1)).Equals(NewB2(1))); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False True False False False False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record A(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (7,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(7, 15), // (11,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(11, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<P>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<P>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); } [Fact] public void Equality_06() { var source = @" using System; using static System.Console; record A; record B : A { protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().First(); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True True False False True False False False True False False True True").VerifyDiagnostics( // (8,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 25) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_07() { var source = @"using System; using static System.Console; record A; record B : A; record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new B()).Equals(new A())); WriteLine(((A)new B()).Equals(new B())); WriteLine(((A)new B()).Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(((B)new C()).Equals(new A())); WriteLine(((B)new C()).Equals(new B())); WriteLine(((B)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); WriteLine(((IEquatable<A>)new B()).Equals(new A())); WriteLine(((IEquatable<A>)new B()).Equals(new B())); WriteLine(((IEquatable<A>)new B()).Equals(new C())); WriteLine(((IEquatable<A>)new C()).Equals(new A())); WriteLine(((IEquatable<A>)new C()).Equals(new B())); WriteLine(((IEquatable<A>)new C()).Equals(new C())); WriteLine(((IEquatable<B>)new C()).Equals(new A())); WriteLine(((IEquatable<B>)new C()).Equals(new B())); WriteLine(((IEquatable<B>)new C()).Equals(new C())); WriteLine(((IEquatable<C>)new C()).Equals(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False True False False False True False False True True False True False False False True False False True True").VerifyDiagnostics(); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.GetHashCode"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); ImmutableArray<Symbol> cEquals = comp.GetMembers("C.Equals"); VerifyVirtualMethods(cEquals, ("System.Boolean C.Equals(C? other)", false), ("System.Boolean C.Equals(B? other)", true), ("System.Boolean C.Equals(System.Object? obj)", true)); var baseEquals = cEquals[1]; Assert.Equal("System.Boolean C.Equals(B? other)", baseEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, baseEquals.DeclaredAccessibility); Assert.True(baseEquals.IsOverride); Assert.True(baseEquals.IsSealed); Assert.True(baseEquals.IsImplicitlyDeclared); } private static void VerifyVirtualMethod(MethodSymbol method, bool isOverride) { Assert.Equal(!isOverride, method.IsVirtual); Assert.Equal(isOverride, method.IsOverride); Assert.True(method.IsMetadataVirtual()); Assert.Equal(!isOverride, method.IsMetadataNewSlot()); } private static void VerifyVirtualMethods(ImmutableArray<Symbol> members, params (string displayString, bool isOverride)[] values) { Assert.Equal(members.Length, values.Length); for (int i = 0; i < members.Length; i++) { var method = (MethodSymbol)members[i]; (string displayString, bool isOverride) = values[i]; Assert.Equal(displayString, method.ToTestDisplayString(includeNonNullable: true)); VerifyVirtualMethod(method, isOverride); } } [WorkItem(44895, "https://github.com/dotnet/roslyn/issues/44895")] [Fact] public void Equality_08() { var source = @" using System; using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B : A { internal B() { } // Use record base call syntax instead internal B(int X, int Y) : base(X) { this.Y = Y; } internal int Y { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)) && NewC(1, 2, 3).GetHashCode() == NewC(1, 2, 3).GetHashCode()); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. var verifier = CompileAndVerify(source, expectedOutput: @"True True False False True False False False True False True False False True False False False True False False True True").VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (15,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(15, 25), // (17,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(17, 14), // (17,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(17, 21), // (17,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(17, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int C.<Z>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_09() { var source = @"using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B(int X, int Y) : A { internal B() : this(0, 0) { } // Use record base call syntax instead internal int Y { get; set; } } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().ElementAt(1); Assert.Equal("B", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False False False False True False False False True False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (12,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 14), // (12,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 21), // (12,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(12, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); } [Fact] public void Equality_11() { var source = @"using System; record A { protected virtual Type EqualityContract => typeof(object); } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { Console.WriteLine(new A().Equals(new A())); Console.WriteLine(new A().Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new A())); Console.WriteLine(new B1((object)null).Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new B2((object)null))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False False True False").VerifyDiagnostics(); } [Fact] public void Equality_12() { var source = @"using System; abstract record A { public A() { } protected abstract Type EqualityContract { get; } } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { var b1 = new B1((object)null); var b2 = new B2((object)null); Console.WriteLine(b1.Equals(b1)); Console.WriteLine(b1.Equals(b2)); Console.WriteLine(((A)b1).Equals(b1)); Console.WriteLine(((A)b1).Equals(b2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False").VerifyDiagnostics(); } [Fact] public void Equality_13() { var source = @"record A { protected System.Type EqualityContract => typeof(A); } record B : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract => typeof(A); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 27), // (5,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(5, 8)); } [Fact] public void Equality_14() { var source = @"record A; record B : A { protected sealed override System.Type EqualityContract => typeof(B); } record C : B; "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (4,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract => typeof(B); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(4, 43), // (6,8): error CS0239: 'C.EqualityContract': cannot override inherited member 'B.EqualityContract' because it is sealed // record C : B; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.EqualityContract", "B.EqualityContract").WithLocation(6, 8)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Type B.EqualityContract.get", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "B..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Equality_15() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B1 o) => base.Equals((A)o); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(B2); public virtual bool Equals(B2 o) => base.Equals((A)o); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(1))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_16() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B1 b) => base.Equals((A)b); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B2 b) => base.Equals((A)b); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(2))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_17() { var source = @"using static System.Console; record A; record B1(int P) : A { } record B2(int P) : A { } class Program { static void Main() { WriteLine(new B1(1).Equals(new B1(1))); WriteLine(new B1(1).Equals(new B1(2))); WriteLine(new B2(3).Equals(new B2(3))); WriteLine(new B2(3).Equals(new B2(4))); WriteLine(((A)new B1(1)).Equals(new B1(1))); WriteLine(((A)new B1(1)).Equals(new B1(2))); WriteLine(((A)new B2(3)).Equals(new B2(3))); WriteLine(((A)new B2(3)).Equals(new B2(4))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False True False True False").VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B1").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B1..ctor(System.Int32 P)", "System.Type B1.EqualityContract.get", "System.Type B1.EqualityContract { get; }", "System.Int32 B1.<P>k__BackingField", "System.Int32 B1.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B1.P.init", "System.Int32 B1.P { get; init; }", "System.String B1.ToString()", "System.Boolean B1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B1.op_Inequality(B1? left, B1? right)", "System.Boolean B1.op_Equality(B1? left, B1? right)", "System.Int32 B1.GetHashCode()", "System.Boolean B1.Equals(System.Object? obj)", "System.Boolean B1.Equals(A? other)", "System.Boolean B1.Equals(B1? other)", "A B1." + WellKnownMemberNames.CloneMethodName + "()", "B1..ctor(B1 original)", "void B1.Deconstruct(out System.Int32 P)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Equality_18(bool useCompilationReference) { var sourceA = @"public record A;"; var comp = CreateCompilation(sourceA); comp.VerifyDiagnostics(); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); var sourceB = @"record B : A;"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); } [Fact] public void Equality_19() { var source = @"using static System.Console; record A<T>; record B : A<int>; class Program { static void Main() { WriteLine(new A<int>().Equals(new A<int>())); WriteLine(new A<int>().Equals(new B())); WriteLine(new B().Equals(new A<int>())); WriteLine(new B().Equals(new B())); WriteLine(((A<int>)new B()).Equals(new A<int>())); WriteLine(((A<int>)new B()).Equals(new B())); WriteLine(new B().Equals((A<int>)new B())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False True False True True").VerifyDiagnostics(); verifier.VerifyIL("A<T>.Equals(A<T>)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A<T>.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A<T>.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A<int>)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A<int>.Equals(A<int>)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_20() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1) ); } [Fact] public void Equality_21() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] [WorkItem(44988, "https://github.com/dotnet/roslyn/issues/44988")] public void Equality_22() { var source = @" record C { int x = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used // int x = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(4, 9) ); } [Fact] public void IEquatableT_01() { var source = @"record A<T>; record B : A<int>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); F(new B()); F<A<int>>(new B()); F<B>(new B()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0411: The type arguments for method 'Program.F<T>(IEquatable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(new B()); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.IEquatable<T>)").WithLocation(11, 9)); } [Fact] public void IEquatableT_02() { var source = @"using System; record A; record B<T> : A; record C : B<int>; class Program { static string F<T>(IEquatable<T> t) { return typeof(T).Name; } static void Main() { Console.WriteLine(F(new A())); Console.WriteLine(F<A>(new C())); Console.WriteLine(F<B<int>>(new C())); Console.WriteLine(F<C>(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A A B`1 C").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @"#nullable enable using System; record A<T> : IEquatable<A<T>> { } record B : A<object>, IEquatable<A<object>>, IEquatable<B?>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_04() { var source = @"using System; record A<T> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)").VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_05() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } record C : A<object>, IEquatable<A<object>>, IEquatable<C> { } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)", symbolValidator: m => { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("B.Equals(B)", b.FindImplementationForInterfaceMember(b.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal("C.Equals(C?)", c.FindImplementationForInterfaceMember(c.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); }).VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: '{B}' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_06() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } bool IEquatable<A<T>>.Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { bool IEquatable<A<object>>.Equals(A<object> other) => Report(""B.Equals(A<object>)""); bool IEquatable<B>.Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(A<object>) B.Equals(B)").VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_07() { var source = @"using System; record A<T> : IEquatable<B1>, IEquatable<B2> { bool IEquatable<B1>.Equals(B1 other) => false; bool IEquatable<B2>.Equals(B2 other) => false; } record B1 : A<object>; record B2 : A<int>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B1"); AssertEx.Equal(new[] { "System.IEquatable<B1>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B2>", "System.IEquatable<A<System.Object>>", "System.IEquatable<B1>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B2"); AssertEx.Equal(new[] { "System.IEquatable<B2>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<A<System.Int32>>", "System.IEquatable<B2>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_08() { var source = @"interface I<T> { } record A<T> : I<A<T>> { } record B : A<object>, I<A<object>>, I<B> { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_09() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T>; record B : A<int>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_10() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T> : System.IEquatable<A<T>>; record B : A<int>, System.IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,22): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<A<T>>").WithArguments("IEquatable<>", "System").WithLocation(1, 22), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8), // (2,27): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<B>").WithArguments("IEquatable<>", "System").WithLocation(2, 27)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_11() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"using System; record A<T> : IEquatable<A<T>>; record B : A<int>, IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,15): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<A<T>>").WithArguments("IEquatable<>").WithLocation(2, 15), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(3, 8), // (3,20): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<B>").WithArguments("IEquatable<>").WithLocation(3, 20)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_12() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); void Other(); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A; class Program { static void Main() { System.IEquatable<A> a = new A(); _ = a.Equals(null); } }"; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0535: 'A' does not implement interface member 'IEquatable<A>.Other()' // record A; Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("A", "System.IEquatable<A>.Other()").WithLocation(1, 8)); } [Fact] public void IEquatableT_13() { var source = @"record A { internal virtual bool Equals(A other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,8): error CS0737: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is not public. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(1, 8), // (3,27): error CS8873: Record member 'A.Equals(A)' must be public. // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 27), // (3,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 27) ); } [Fact] public void IEquatableT_14() { var source = @"record A { public bool Equals(A other) => false; } record B : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,17): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 17), // (3,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 17), // (5,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(5, 8)); } [WorkItem(45026, "https://github.com/dotnet/roslyn/issues/45026")] [Fact] public void IEquatableT_15() { var source = @"using System; record R { bool IEquatable<R>.Equals(R other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void IEquatableT_16() { var source = @"using System; class A<T> { record B<U> : IEquatable<B<T>> { bool IEquatable<B<T>>.Equals(B<T> other) => false; bool IEquatable<B<U>>.Equals(B<U> other) => false; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0695: 'A<T>.B<U>' cannot implement both 'IEquatable<A<T>.B<T>>' and 'IEquatable<A<T>.B<U>>' because they may unify for some type parameter substitutions // record B<U> : IEquatable<B<T>> Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "B").WithArguments("A<T>.B<U>", "System.IEquatable<A<T>.B<T>>", "System.IEquatable<A<T>.B<U>>").WithLocation(4, 12)); } [Fact] public void InterfaceImplementation() { var source = @" interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; set; } } record R(int P1) : I { public int P2 { get; init; } int I.P3 { get; set; } public static void Main() { I r = new R(42) { P2 = 43 }; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)", verify: Verification.Skipped /* init-only */); } [Fact] public void Initializers_01() { var src = @" using System; record C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_05() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => 100 + X++) { Func<int> Y = () => 200 + X++; Func<int> Z = () => 300 + X++; public static void Main() { var c = new C(1); Console.WriteLine(c.Y()); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 101 202 303 ").VerifyDiagnostics(); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut() { var src = @" record R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 8), // (2,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 10), // (2,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut_WithBase() { var src = @" record Base(int I); record R(ref int P1, out int P2) : Base(P2 = 1); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 10), // (3,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(3, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_In() { var src = @" record R(in int P1); public class C { public static void Main() { var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,10): error CS0027: Keyword 'this' is not available in the current context // record R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 10) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_Params() { var src = @" record R(params int[] Array); public class C { public static void Main() { var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue() { var src = @" record R(int P = 42) { public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" record R(int P = 1) { public int P { get; init; } = 42; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int R.<P>k__BackingField"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: nop IL_000f: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "0", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" record R(int P = 42) { public int P { get; init; } = P; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<P>k__BackingField"" IL_0007: ldarg.0 IL_0008: call ""object..ctor()"" IL_000d: nop IL_000e: ret }"); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void AttributesOnPrimaryConstructorParameters_02() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_03() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public abstract int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_04() { string source = @" [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true) ] public class A : System.Attribute { } public record Test( [method: A] int P1) { [method: A] void M1() {} } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new string[] { }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (8,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property, param'. All attributes in this block will be ignored. // [method: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property, param").WithLocation(8, 6) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_05() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public virtual int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,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. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,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. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_06() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,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. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,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. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_07() { string source = @" [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (20,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(20, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_08() { string source = @" #nullable enable using System.Diagnostics.CodeAnalysis; record C<T>([property: NotNull] T? P1, T? P2) where T : class { protected C(C<T> other) { T x = P1; T y = P2; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(10, 15) ); } [Fact] public void AttributesOnPrimaryConstructorParameters_09_CallerMemberName() { string source = @" using System.Runtime.CompilerServices; record R([CallerMemberName] string S = """"); class C { public static void Main() { var r = new R(); System.Console.Write(r.S); } } "; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, expectedOutput: "Main", parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, verify: Verification.Skipped /* init-only */); comp.VerifyDiagnostics(); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,23): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(10, 23), // (11,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(11, 25) ); CompileAndVerify(comp, expectedOutput: "(R, R2)", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void AccessCheckProtected03() { CSharpCompilation c = CreateCompilation(@" record X<T> { } record A { } record B { record C : X<C.D.E> { protected record D : A { public record E { } } } } ", targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, c.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (c.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } else { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0050: Inconsistent accessibility: return type 'X<B.C.D.E>' is less accessible than method 'B.C.<Clone>$()' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisReturnType, "C").WithArguments("B.C.<Clone>$()", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } } [Fact] public void TestTargetType_Abstract() { var source = @" abstract record C { void M() { C x0 = new(); var x1 = (C)new(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C' // C x0 = new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16), // (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C' // var x1 = (C)new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21) ); } [Fact] public void CyclicBases4() { var text = @" record A<T> : B<A<T>> { } record B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (2,8): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>' // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>").WithLocation(2, 8), // (3,8): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>' // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>").WithLocation(3, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (3,8): error CS0115: 'B<T>.EqualityContract': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.Equals(object?)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.Equals(object?)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.GetHashCode()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.GetHashCode()").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.PrintMembers(StringBuilder)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.ToString()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.ToString()").WithLocation(3, 8) ); } [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" record B { } record C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()") ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseTypes() { var source = @" public record Base<T> { } public partial record C1 : Base<(int a, int b)> { } public partial record C1 : Base<(int notA, int notB)> { } public partial record C2 : Base<(int a, int b)> { } public partial record C2 : Base<(int, int)> { } public partial record C3 : Base<(int a, int b)> { } public partial record C3 : Base<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,23): error CS0263: Partial declarations of 'C2' must not specify different base classes // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 23), // (3,23): error CS0263: Partial declarations of 'C1' must not specify different base classes // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 23), // (5,23): error CS0115: 'C2.ToString()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.EqualityContract': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(5, 23), // (5,23): error CS0115: 'C2.Equals(object?)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(5, 23), // (5,23): error CS0115: 'C2.GetHashCode()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 23), // (3,23): error CS0115: 'C1.ToString()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.ToString()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.EqualityContract': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.EqualityContract").WithLocation(3, 23), // (3,23): error CS0115: 'C1.Equals(object?)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.Equals(object?)").WithLocation(3, 23), // (3,23): error CS0115: 'C1.GetHashCode()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.GetHashCode()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public class C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1)); } [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } record Goo<T> { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2) ); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } record A { } record B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record R; "; CreateCompilation(source).VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // sealed static record R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void ConversionToBase() { var source = @" public record Base<T> { } public record Derived : Base<(int a, int b)> { public static explicit operator Base<(int, int)>(Derived x) { return null; } public static explicit operator Derived(Base<(int, int)> x) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed // public static explicit operator Derived(Base<(int, int)> x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37), // (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed // public static explicit operator Base<(int, int)>(Derived x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37) ); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public record B { public static implicit operator B(D d) // CS0554 { return null; } } public record D : B {} "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public record iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [Fact] public void StaticBasePartial() { var text = @" static record NV { } public partial record C1 { } partial record C1 : NV { } public partial record C1 { } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } else { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0050: Inconsistent accessibility: return type 'NV' is less accessible than method 'C1.<Clone>$()' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisReturnType, "C1").WithArguments("C1.<Clone>$()", "NV").WithLocation(6, 23), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record R(int I) { R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 15) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithMultipleBaseTypes() { var source = @" record Base1; record Base2; record R : Base1, Base2 { }"; CreateCompilation(source).VerifyDiagnostics( // (4,19): error CS1721: Class 'R' cannot have multiple base classes: 'Base1' and 'Base2' // record R : Base1, Base2 Diagnostic(ErrorCode.ERR_NoMultipleInheritance, "Base2").WithArguments("R", "Base1", "Base2").WithLocation(4, 19) ); } [Fact] public void RecordWithInterfaceBeforeBase() { var source = @" record Base; interface I { } record R : I, Base; "; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS1722: Base class 'Base' must come before any interfaces // record R : I, Base; Diagnostic(ErrorCode.ERR_BaseClassMustBeFirst, "Base").WithArguments("Base").WithLocation(4, 15) ); } [Fact] public void RecordLoadedInVisualBasicDisplaysAsClass() { var src = @" public record A; "; var compRef = CreateCompilation(src).EmitToImageReference(); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: new[] { compRef }); var symbol = vbComp.GlobalNamespace.GetTypeMember("A"); Assert.False(symbol.IsRecord); Assert.Equal("class A", SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void AnalyzerActions_01() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} class Attr1 : System.Attribute {} class Attr2 : System.Attribute {} class Attr3 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount18); Assert.Equal(1, analyzer.FireCount19); Assert.Equal(1, analyzer.FireCount20); Assert.Equal(1, analyzer.FireCount21); Assert.Equal(1, analyzer.FireCount22); Assert.Equal(1, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(1, analyzer.FireCount27); Assert.Equal(1, analyzer.FireCount28); Assert.Equal(1, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; public int FireCount18; public int FireCount19; public int FireCount20; public int FireCount21; public int FireCount22; public int FireCount23; public int FireCount24; public int FireCount25; public int FireCount26; public int FireCount27; public int FireCount28; public int FireCount29; public int FireCount30; public int FireCount31; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "1": Interlocked.Increment(ref FireCount1); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "2": Interlocked.Increment(ref FireCount2); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount3); Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount4); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "5": Interlocked.Increment(ref FireCount5); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount15); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 1": Interlocked.Increment(ref FireCount16); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 4": Interlocked.Increment(ref FireCount6); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": base(5)": Interlocked.Increment(ref FireCount7); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCount8); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); } protected void Handle5(SyntaxNodeAnalysisContext context) { var baseType = (PrimaryConstructorBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "A(2)": switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount9); break; case "B": Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } Assert.Same(baseType.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount10); break; case "B": Interlocked.Increment(ref FireCount11); break; case "A": Interlocked.Increment(ref FireCount12); break; case "C": Interlocked.Increment(ref FireCount13); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "A": switch (identifier.Parent!.ToString()) { case "A(2)": Interlocked.Increment(ref FireCount18); Assert.Equal("B", context.ContainingSymbol.ToTestDisplayString()); break; case "A": Interlocked.Increment(ref FireCount19); Assert.Equal(SyntaxKind.SimpleBaseType, identifier.Parent.Kind()); Assert.Equal("C", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } break; case "Attr1": Interlocked.Increment(ref FireCount24); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr2": Interlocked.Increment(ref FireCount25); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr3": Interlocked.Increment(ref FireCount26); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCount20); break; case "B": Interlocked.Increment(ref FireCount21); break; case "C": Interlocked.Increment(ref FireCount22); break; default: Assert.True(false); break; } break; case "A": switch (context.ContainingSymbol.ToTestDisplayString()) { case "C": Interlocked.Increment(ref FireCount23); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCount27); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr2]int Y = 1)": Interlocked.Increment(ref FireCount28); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr3]int Z = 4)": Interlocked.Increment(ref FireCount29); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(2)": Interlocked.Increment(ref FireCount30); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "(5)": Interlocked.Increment(ref FireCount31); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } protected void Handle1(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(SyntaxKind.ConstructorDeclaration, context.Operation.Syntax.Kind()); break; default: Assert.True(false); break; } } protected void Handle2(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount4); Assert.Equal(SyntaxKind.PrimaryConstructorBaseType, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(2)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'A(2)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount5); Assert.Equal(SyntaxKind.BaseConstructorInitializer, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: ': base(5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); break; default: Assert.True(false); break; } } protected void Handle3(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; case "200": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); break; case "1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount9); break; case "2": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount10); break; case "300": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); break; case "4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); break; case "5": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount13); break; case "3": Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } } protected void Handle4(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; case "= 1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount15); break; case "= 4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount16); break; default: Assert.True(false); break; } } protected void Handle5(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_06_Analyzer : AnalyzerActions_04_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount100); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount200); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount300); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount400); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; default: Assert.True(false); break; } } private void RegisterOperationAction(OperationBlockStartAnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } private void Handle6(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1000); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2000); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3000); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4000); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(0, analyzer.FireCount10); Assert.Equal(0, analyzer.FireCount11); Assert.Equal(0, analyzer.FireCount12); Assert.Equal(0, analyzer.FireCount13); Assert.Equal(0, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(0, analyzer.FireCount17); Assert.Equal(0, analyzer.FireCount18); Assert.Equal(0, analyzer.FireCount19); Assert.Equal(0, analyzer.FireCount20); Assert.Equal(0, analyzer.FireCount21); Assert.Equal(0, analyzer.FireCount22); Assert.Equal(0, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(0, analyzer.FireCount27); Assert.Equal(0, analyzer.FireCount28); Assert.Equal(0, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount200); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount300); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2000); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3000); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] [WorkItem(46657, "https://github.com/dotnet/roslyn/issues/46657")] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; public record X(int a) { public static void Main() { foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } } public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); } [Fact] public void DefaultCtor_01() { var src = @" record C { } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_02() { var src = @" record B(int x); record C : B { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_03() { var src = @" record C { public C(C c){} } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_04() { var src = @" record B(int x); record C : B { public C(C c) : base(c) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_05() { var src = @" record C(int x); class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.C(int)' // _ = new C(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("x", "C.C(int)").WithLocation(8, 17) ); } [Fact] public void DefaultCtor_06() { var src = @" record C { C(int x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] public void DefaultCtor_07() { var src = @" class C { C(C x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_RecordWithStaticMembers() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { public static int field1 = 44; public const int field2 = 44; public static int P1 { set { } } public static int P2 { get { return 1; } set { } } public static int P3 { get { return 1; } } } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_Cycle_01() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public Rec Inner; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_02() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Base { public Rec Inner; } public record Rec : Base { } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_03() { var src = @" using System; var rec = new Rec(); rec.RecStruct.Rec = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_04() { var src = @" public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; var comp = CreateCompilation(src); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""RecStruct = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""RecStruct Rec.RecStruct"" IL_0018: constrained. ""RecStruct"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret }"); comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack); verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""RecStruct = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""RecStruct Rec.RecStruct"" IL_0013: constrained. ""RecStruct"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] [WorkItem(50040, "https://github.com/dotnet/roslyn/issues/50040")] public void RaceConditionInAddMembers() { var src = @" #nullable enable using System; using System.Linq.Expressions; using System.Threading.Tasks; var collection = new Collection<Hamster>(); Hamster h = null!; await collection.MethodAsync(entity => entity.Name! == ""bar"", h); public record Collection<T> where T : Document { public Task MethodAsync<TDerived>(Expression<Func<TDerived, bool>> filter, TDerived td) where TDerived : T => throw new NotImplementedException(); public Task MethodAsync<TDerived2>(Task<TDerived2> filterDefinition, TDerived2 td) where TDerived2 : T => throw new NotImplementedException(); } public sealed record HamsterCollection : Collection<Hamster> { } public abstract class Document { } public sealed class Hamster : Document { public string? Name { get; private set; } } "; for (int i = 0; i < 100; i++) { var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); } } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact, WorkItem(53912, "https://github.com/dotnet/roslyn/issues/53912")] public void XmlDoc_CrefToPositionalProperty_Test53912() { var source = @" namespace NamespaceA { /// <summary> /// A sample record type /// </summary> /// <param name=""Prop1""> /// A property /// </param> public record LinkDestinationRecord(string Prop1); /// <summary> /// Simple class. /// </summary> public class LinkingClass { /// <inheritdoc cref=""LinkDestinationRecord.Prop1"" /> public string Prop1A { get; init; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, assemblyName: "Test"); var actual = GetDocumentationCommentText(comp); // the cref becomes `P:...` var expected = (@"<?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:NamespaceA.LinkDestinationRecord""> <summary> A sample record type </summary> <param name=""Prop1""> A property </param> </member> <member name=""M:NamespaceA.LinkDestinationRecord.#ctor(System.String)""> <summary> A sample record type </summary> <param name=""Prop1""> A property </param> </member> <member name=""T:NamespaceA.LinkingClass""> <summary> Simple class. </summary> </member> <member name=""P:NamespaceA.LinkingClass.Prop1A""> <inheritdoc cref=""P:NamespaceA.LinkDestinationRecord.Prop1"" /> </member> </members> </doc>"); Assert.Equal(expected, actual); } [Fact] public void XmlDoc_RecordClass() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record class C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Error() { var src = @" /// <summary>Summary</summary> /// <param name=""Error""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18), // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Duplicate() { var src = @" /// <summary>Summary</summary> /// <param name=""I1""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12), // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef() { var src = @" /// <summary>Summary <paramref name=""I1""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary <paramref name=""I1""/></summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef_Error() { var src = @" /// <summary>Summary <paramref name=""Error""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,38): warning CS1734: XML comment on 'C' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C").WithLocation(2, 38), // (2,38): warning CS1734: XML comment on 'C.C(int)' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C.C(int)").WithLocation(2, 38) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_WithExplicitProperty() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1) { /// <summary>Property summary</summary> public int I1 { get; init; } = I1; } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal( @"<member name=""P:C.I1""> <summary>Property summary</summary> </member> ", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_EmptyParameterList() { var src = @" /// <summary>Summary</summary> public record C(); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.IsEmpty).Single(); Assert.Equal( @"<member name=""M:C.#ctor""> <summary>Summary</summary> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond() { var src = @" public partial record C; /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(3, 18), // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(6, 23) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocSecond() { var src = @" public partial record C(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'C.C(int)' // public partial record C(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C.C(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record C(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, cConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record D(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""I1"">Description2 for I1</param> public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description2 for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""I1"">Description2 for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(6, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested() { var src = @" /// <summary>Summary</summary> public class Outer { /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); Assert.Equal( @"<member name=""T:Outer.C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested_ReferencingOuterParam() { var src = @" /// <summary>Summary</summary> /// <param name=""O1"">Description for O1</param> public record Outer(object O1) { /// <summary>Summary</summary> public int P1 { get; set; } /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> /// <param name=""O1"">Error O1</param> /// <param name=""P1"">Error P1</param> /// <param name=""C"">Error C</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22) ); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> <param name=""O1"">Error O1</param> <param name=""P1"">Error P1</param> <param name=""C"">Error C</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact, WorkItem(51590, "https://github.com/dotnet/roslyn/issues/51590")] public void SealedIncomplete() { var source = @" public sealed record("; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS1001: Identifier expected // public sealed record( Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 21), // (2,22): error CS1026: ) expected // public sealed record( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(2, 22), // (2,22): error CS1514: { expected // public sealed record( Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 22), // (2,22): error CS1513: } expected // public sealed record( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 22) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field_HiddenWithConstant() { var source = @" public record Base { public int I = 0; public Base(int ignored) { } } public record C(int I) : Base(I) { public const int I = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,22): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const int I = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 22) ); } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 10) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_TwoParameters() { var source = @" var a = new A(42, 43); System.Console.Write(a.Y); System.Console.Write("" - ""); a.Deconstruct(out int x, out int y); System.Console.Write(y); record A(int X, int Y) { public int X = X; public int Y = Y; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "43 - 43"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: ldfld ""int A.Y"" IL_000f: stind.i4 IL_0010: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_UnusedParameter() { var source = @" record A(int X) { public int X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (4,16): warning CS0649: Field 'A.X' is never assigned to, and will always have its default value 0 // public int X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("A.X", "0").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 0; } public record C(int I) : Base { public int I = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int C.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst_FieldInBase() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 0; } public record C(int I) : Base { public int I { get; set; } = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I { get; set; } = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int C.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int Base.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase_StaticFieldInDerivedType() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I = 42; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I { get; set; } = 42; } "; comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I { get; set; } = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); } [Fact] public void FieldAsPositionalMember_Static() { var source = @" record A(int X) { public static int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14) ); } [Fact] public void FieldAsPositionalMember_Const() { var src = @" record C(int P) { const int P = 4; } record C2(int P) { const int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (6,15): error CS8866: Record member 'C2.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C2(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C2.P", "int", "P").WithLocation(6, 15), // (6,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C2(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(6, 15), // (8,15): error CS0110: The evaluation of the constant value for 'C2.P' involves a circular definition // const int P = P; Diagnostic(ErrorCode.ERR_CircConstValue, "P").WithArguments("C2.P").WithLocation(8, 15) ); } [Fact] public void FieldAsPositionalMember_Volatile() { var src = @" record C(int P) { public volatile int P = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_DifferentAccessibility() { var src = @" record C(int P) { private int P = P; } record C2(int P) { protected int P = P; } record C3(int P) { internal int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_WrongType() { var src = @" record C(int P) { public string P = null; public int Q = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_DeconstructInSource() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } public void Deconstruct(out int i) { i = 0; } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_WithNew() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) // 1 { public new void I() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) // 1 Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithGenericMethod() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I<T>() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (11,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(11, 21), // (13,17): warning CS0108: 'C.I<T>()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I<T>() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I<T>()", "Base.I").WithLocation(13, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_FromGrandBase() { var source = @" public record GrandBase { public int I { get; set; } = 42; } public record Base : GrandBase { public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (10,21): error CS8913: The positional member 'GrandBase.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("GrandBase.I").WithLocation(10, 21), // (12,17): warning CS0108: 'C.I()' hides inherited member 'GrandBase.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "GrandBase.I").WithLocation(12, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int Item { get; set; } = 42; public Base(int ignored) { } } public record C(int Item) : Base(Item) { public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.Item.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer_WithIndexerName() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { [System.Runtime.CompilerServices.IndexerName(""I"")] public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithType() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public class I { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,18): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public class I { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 18) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithEvent() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public event System.Action I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,32): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public event System.Action I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 32), // (9,32): warning CS0067: The event 'C.I' is never used // public event System.Action I; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "I").WithArguments("C.I").WithLocation(9, 32) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithConstant() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public const string I = null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,25): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const string I = null; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 25) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase() { var source = @" abstract record Base { public abstract int I { get; init; } } record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): warning CS0108: 'Derived.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I() { return 0; } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase_AbstractInDerived() { var source = @" abstract record Base { public abstract int I { get; init; } } abstract record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): error CS0533: 'Derived.I()' hides inherited abstract member 'Base.I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record R(int X) : I() { } record R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 21), // (10,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_RecordClass() { var src = @" public interface I { } record class R(int X) : I() { } record class R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,26): error CS8861: Unexpected argument list. // record class R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 26), // (10,27): error CS8861: Unexpected argument list. // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 27), // (10,27): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 27) ); } [Fact] public void BaseErrorTypeWithParameters() { var src = @" record R2(int X) : Error(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'R2.ToString()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.EqualityContract': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R2.Equals(object?)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R2.GetHashCode()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.PrintMembers(StringBuilder)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,20): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 20), // (2,25): error CS1729: 'Error' does not contain a constructor that takes 1 arguments // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("Error", "1").WithLocation(2, 25) ); } [Fact] public void BaseDynamicTypeWithParameters() { var src = @" record R(int X) : dynamic(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS1965: 'R': cannot derive from the dynamic type // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("R").WithLocation(2, 19), // (2,26): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 26) ); } [Fact] public void BaseTypeParameterTypeWithParameters() { var src = @" class C<T> { record R(int X) : T(X) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0689: Cannot derive from 'T' because it is a type parameter // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_DerivingFromATyVar, "T").WithArguments("T").WithLocation(4, 23), // (4,24): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(4, 24) ); } [Fact] public void BaseObjectTypeWithParameters() { var src = @" record R(int X) : object(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,25): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : object(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 25) ); } [Fact] public void BaseValueTypeTypeWithParameters() { var src = @" record R(int X) : System.ValueType(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS0644: 'R' cannot derive from special class 'ValueType' // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.ValueType").WithArguments("R", "System.ValueType").WithLocation(2, 19), // (2,35): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 35) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record R : I() { } record R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // record R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // record R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void InterfaceWithParameters_Class() { var src = @" public interface I { } class C : I() { } class C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,12): error CS8861: Unexpected argument list. // class C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 12), // (10,13): error CS8861: Unexpected argument list. // class C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 13) ); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [CombinatorialData] public void CrossAssemblySupportingAndNotSupportingCovariantReturns(bool useCompilationReference) { var sourceA = @"public record B(int I) { } public record C(int I) : B(I);"; var compA = CreateEmptyCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20)); compA.VerifyDiagnostics(); Assert.False(compA.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var actualMembers = compA.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 I)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(B? other)", "System.Boolean C.Equals(C? other)", "B C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 I)", }; AssertEx.Equal(expectedMembers, actualMembers); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = "record D(int I) : C(I);"; // CS1701: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy var compB = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions("CS1701", ReportDiagnostic.Suppress), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compB.VerifyDiagnostics(); Assert.True(compB.Assembly.RuntimeSupportsCovariantReturnsOfClasses); actualMembers = compB.GetMember<NamedTypeSymbol>("D").GetMembers().ToTestDisplayStrings(); expectedMembers = new[] { "D..ctor(System.Int32 I)", "System.Type D.EqualityContract.get", "System.Type D.EqualityContract { get; }", "System.String D.ToString()", "System.Boolean D." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean D.op_Inequality(D? left, D? right)", "System.Boolean D.op_Equality(D? left, D? right)", "System.Int32 D.GetHashCode()", "System.Boolean D.Equals(System.Object? obj)", "System.Boolean D.Equals(C? other)", "System.Boolean D.Equals(D? other)", "D D." + WellKnownMemberNames.CloneMethodName + "()", "D..ctor(D original)", "void D.Deconstruct(out System.Int32 I)" }; AssertEx.Equal(expectedMembers, actualMembers); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { public class RecordTests : CompilingTestBase { private static CSharpCompilation CreateCompilation(CSharpTestSource source) => CSharpTestBase.CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); private CompilationVerifier CompileAndVerify( CSharpTestSource src, string? expectedOutput = null, IEnumerable<MetadataReference>? references = null) => base.CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, expectedOutput: expectedOutput, parseOptions: TestOptions.RegularPreview, references: references, // init-only is unverifiable verify: Verification.Skipped); [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion() { var src1 = @" class Point(int x, int y); "; var src2 = @" record Point { } "; var src3 = @" record Point(int x, int y); "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS0116: A namespace cannot directly contain members such as fields or methods // record Point { } Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "Point").WithLocation(2, 8), // (2,8): error CS0548: '<invalid-global-code>.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("<invalid-global-code>.Point").WithLocation(2, 8) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS8805: Program using top-level statements must be an executable. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "record Point(int x, int y);").WithLocation(2, 1), // (2,1): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "record Point(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 1), // (2,1): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(2, 1), // (2,8): error CS8112: Local function 'Point(int, int)' must declare a body because it is not marked 'static extern'. // record Point(int x, int y); Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "Point").WithArguments("Point(int, int)").WithLocation(2, 8), // (2,8): warning CS8321: The local function 'Point' is declared but never used // record Point(int x, int y); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "Point").WithArguments("Point").WithLocation(2, 8) ); comp = CreateCompilation(src1, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,12): error CS8805: Program using top-level statements must be an executable. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 12), // (2,12): error CS8803: Top-level statements must precede namespace and type declarations. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 12), // (2,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 12), // (2,13): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 13), // (2,13): error CS0165: Use of unassigned local variable 'x' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 13), // (2,20): error CS8185: A declaration is not allowed in this context. // class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'y' // class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 20) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); var point = comp.GlobalNamespace.GetTypeMember("Point"); Assert.True(point.IsReferenceType); Assert.False(point.IsValueType); Assert.Equal(TypeKind.Class, point.TypeKind); Assert.Equal(SpecialType.System_Object, point.BaseTypeNoUseSiteDiagnostics.SpecialType); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordLanguageVersion_Nested() { var src1 = @" class C { class Point(int x, int y); } "; var src2 = @" class D { record Point { } } "; var src3 = @" class E { record Point(int x, int y); } "; var comp = CreateCompilation(src1, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0548: 'D.Point': property or indexer must have at least one accessor // record Point { } Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "Point").WithArguments("D.Point").WithLocation(4, 12) ); comp = CreateCompilation(src3, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,5): error CS0246: The type or namespace name 'record' could not be found (are you missing a using directive or an assembly reference?) // record Point(int x, int y); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "record").WithArguments("record").WithLocation(4, 5), // (4,12): error CS0501: 'E.Point(int, int)' must declare a body because it is not marked abstract, extern, or partial // record Point(int x, int y); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "Point").WithArguments("E.Point(int, int)").WithLocation(4, 12) ); comp = CreateCompilation(src1); comp.VerifyDiagnostics( // (4,16): error CS1514: { expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(4, 16), // (4,16): error CS1513: } expected // class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(4, 16), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30), // (4,30): error CS1519: Invalid token ';' in class, struct, or interface member declaration // class Point(int x, int y); Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(4, 30) ); comp = CreateCompilation(src2); comp.VerifyDiagnostics(); comp = CreateCompilation(src3); comp.VerifyDiagnostics(); } [Fact, WorkItem(45900, "https://github.com/dotnet/roslyn/issues/45900")] public void RecordClassLanguageVersion() { var src = @" record class Point(int x, int y); "; var comp = CreateCompilation(src, parseOptions: TestOptions.Regular8, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,1): error CS0116: A namespace cannot directly contain members such as fields or methods // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "record").WithLocation(2, 1), // (2,19): error CS1514: { expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_LbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS1513: } expected // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_RbraceExpected, "(").WithLocation(2, 19), // (2,19): error CS8400: Feature 'top-level statements' is not available in C# 8.0. Please use language version 9.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "(int x, int y);").WithArguments("top-level statements", "9.0").WithLocation(2, 19), // (2,19): error CS8803: Top-level statements must precede namespace and type declarations. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS8805: Program using top-level statements must be an executable. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_SimpleProgramNotAnExecutable, "(int x, int y);").WithLocation(2, 19), // (2,19): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_IllegalStatement, "(int x, int y)").WithLocation(2, 19), // (2,20): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x").WithLocation(2, 20), // (2,20): error CS0165: Use of unassigned local variable 'x' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int x").WithArguments("x").WithLocation(2, 20), // (2,27): error CS8185: A declaration is not allowed in this context. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int y").WithLocation(2, 27), // (2,27): error CS0165: Use of unassigned local variable 'y' // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_UseDefViolation, "int y").WithArguments("y").WithLocation(2, 27) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (2,8): error CS8773: Feature 'record structs' is not available in C# 9.0. Please use language version 10.0 or greater. // record class Point(int x, int y); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "class").WithArguments("record structs", "10.0").WithLocation(2, 8) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics(); } [CombinatorialData] [Theory, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers(bool useCompilationReference) { var lib_src = @" public record RecordA(RecordB B); public record RecordB(int C); "; var lib_comp = CreateCompilation(lib_src); var src = @" class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src, references: new[] { AsReference(lib_comp, useCompilationReference) }); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_SingleCompilation() { var src = @" public record RecordA(RecordB B); public record RecordB(int C); class C { void M(RecordA a, RecordB b) { _ = a.B == b; } } "; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var node = tree.GetRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); Assert.Equal("System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)", model.GetSymbolInfo(node).Symbol.ToTestDisplayString()); } [Fact, WorkItem(49302, "https://github.com/dotnet/roslyn/issues/49302")] public void GetSimpleNonTypeMembers_DirectApiCheck() { var src = @" public record RecordB(); "; var comp = CreateCompilation(src); var b = comp.GlobalNamespace.GetTypeMember("RecordB"); AssertEx.SetEqual(new[] { "System.Boolean RecordB.op_Equality(RecordB? left, RecordB? right)" }, b.GetSimpleNonTypeMembers("op_Equality").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor() { var src = @" record R(R x); #nullable enable record R2(R2? x) { } record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2(R2? x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8), // (7,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R3([System.Diagnostics.CodeAnalysis.NotNull] R3 x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R3").WithLocation(7, 8) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R original)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_Generic() { var src = @" record R<T>(R<T> x); #nullable enable record R2<T>(R2<T?> x) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R<T>(R<T> x); Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8), // (5,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R2<T>(R2<T?> x) { } Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R2").WithLocation(5, 8) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithExplicitCopyCtor() { var src = @" record R(R x) { public R(R x) => throw null; } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,12): error CS0111: Type 'R' already defines a member called 'R' with the same parameter types // public R(R x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R").WithArguments("R", "R").WithLocation(4, 12) ); var r = comp.GlobalNamespace.GetTypeMember("R"); Assert.Equal(new[] { "R..ctor(R x)", "R..ctor(R x)" }, r.GetMembers(".ctor").ToTestDisplayStrings()); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithBase() { var src = @" record Base; record R(R x) : Base; // 1 record Derived(Derived y) : R(y) // 2 { public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 } record Derived2(Derived2 y) : R(y); // 6, 7, 8 record R2(R2 x) : Base { public R2(R2 x) => throw null; // 9, 10 } record R3(R3 x) : Base { public R3(R3 x) : base(x) => throw null; // 11 } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (4,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R x) : Base; // 1 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(4, 8), // (6,30): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived(Derived y) : R(y) // 2 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(6, 30), // (8,12): error CS0111: Type 'Derived' already defines a member called 'Derived' with the same parameter types // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Derived").WithArguments("Derived", "Derived").WithLocation(8, 12), // (8,33): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_AmbigCall, "base").WithArguments("R.R(R)", "R.R(R)").WithLocation(8, 33), // (8,33): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public Derived(Derived y) : base(y) => throw null; // 3, 4, 5 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(8, 33), // (11,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "Derived2").WithLocation(11, 8), // (11,8): error CS8867: No accessible copy constructor found in base type 'R'. // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "Derived2").WithArguments("R").WithLocation(11, 8), // (11,32): error CS0121: The call is ambiguous between the following methods or properties: 'R.R(R)' and 'R.R(R)' // record Derived2(Derived2 y) : R(y); // 6, 7, 8 Diagnostic(ErrorCode.ERR_AmbigCall, "(y)").WithArguments("R.R(R)", "R.R(R)").WithLocation(11, 32), // (15,12): error CS0111: Type 'R2' already defines a member called 'R2' with the same parameter types // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R2").WithArguments("R2", "R2").WithLocation(15, 12), // (15,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public R2(R2 x) => throw null; // 9, 10 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "R2").WithLocation(15, 12), // (20,12): error CS0111: Type 'R3' already defines a member called 'R3' with the same parameter types // public R3(R3 x) : base(x) => throw null; // 11 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "R3").WithArguments("R3", "R3").WithLocation(20, 12) ); } [Fact, WorkItem(49628, "https://github.com/dotnet/roslyn/issues/49628")] public void AmbigCtor_WithPropertyInitializer() { var src = @" record R(R X) { public R X { get; init; } = X; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS8909: The primary constructor conflicts with the synthesized copy constructor. // record R(R X) Diagnostic(ErrorCode.ERR_RecordAmbigCtor, "R").WithLocation(2, 8) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var parameterSyntax = tree.GetRoot().DescendantNodes().OfType<ParameterSyntax>().Single(); var parameter = model.GetDeclaredSymbol(parameterSyntax)!; Assert.Equal("R X", parameter.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, parameter.Kind); Assert.Equal("R..ctor(R X)", parameter.ContainingSymbol.ToTestDisplayString()); var initializerSyntax = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Single(); var initializer = model.GetSymbolInfo(initializerSyntax.Value).Symbol!; Assert.Equal("R X", initializer.ToTestDisplayString()); Assert.Equal(SymbolKind.Parameter, initializer.Kind); Assert.Equal("R..ctor(R X)", initializer.ContainingSymbol.ToTestDisplayString()); } [Fact] public void GetDeclaredSymbolOnAnOutLocalInPropertyInitializer() { var src = @" record R(int I) { public int I { get; init; } = M(out int i) ? i : 0; static bool M(out int i) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // record R(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(2, 14) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var outVarSyntax = tree.GetRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().Single(); var outVar = model.GetDeclaredSymbol(outVarSyntax)!; Assert.Equal("System.Int32 i", outVar.ToTestDisplayString()); Assert.Equal(SymbolKind.Local, outVar.Kind); Assert.Equal("System.Int32 R.<I>k__BackingField", outVar.ContainingSymbol.ToTestDisplayString()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord() { string source = @" public record A(int i,) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i,) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 23) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "? A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32 i, ?)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTrivia() { string source = @" public record A(int i, // A // B , /* C */ ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,23): error CS1031: Type expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 23), // (2,23): error CS1001: Identifier expected // public record A(int i, // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 23), // (4,15): error CS1031: Type expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 15), // (4,15): error CS1001: Identifier expected // , /* C */ ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 15), // (4,15): error CS0102: The type 'A' already contains a definition for '' // , /* C */ ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 15) ); var primaryCtor = comp.GetMember<NamedTypeSymbol>("A").Constructors.First(); Assert.Equal("A..ctor(System.Int32 i, ?, ?)", primaryCtor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(primaryCtor.Parameters[2].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompleteConstructor() { string source = @" public class C { C(int i, ) { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,14): error CS1031: Type expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_TypeExpected, ")").WithLocation(4, 14), // (4,14): error CS1001: Identifier expected // C(int i, ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 14) ); var ctor = comp.GetMember<NamedTypeSymbol>("C").Constructors.Single(); Assert.Equal("C..ctor(System.Int32 i, ?)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithType() { string source = @" public record A(int i, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,28): error CS1001: Identifier expected // public record A(int i, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 28) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A.i { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.Equal("A..ctor(System.Int32 i, System.Int32)", ctor.ToTestDisplayString()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.Equal(0, ctor.Parameters[1].Locations.Single().SourceSpan.Length); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes() { string source = @" public record A(int, string ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,29): error CS1001: Identifier expected // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 29), // (2,29): error CS0102: The type 'A' already contains a definition for '' // public record A(int, string ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 29) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.String A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.String)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_SameType() { string source = @" public record A(int, int ) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(2, 20), // (2,26): error CS1001: Identifier expected // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 26), // (2,26): error CS0102: The type 'A' already contains a definition for '' // public record A(int, int ) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(2, 26) ); var expectedMembers = new[] { "System.Type A.EqualityContract { get; }", "System.Int32 A. { get; init; }", "System.Int32 A. { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("A").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); AssertEx.Equal(new[] { "A..ctor(System.Int32, System.Int32)", "A..ctor(A original)" }, comp.GetMember<NamedTypeSymbol>("A").Constructors.ToTestDisplayStrings()); Assert.IsType<ParameterSyntax>(comp.GetMember<NamedTypeSymbol>("A").Constructors[0].Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46123, "https://github.com/dotnet/roslyn/issues/46123")] public void IncompletePositionalRecord_WithTwoTypes_WithTrivia() { string source = @" public record A(int // A // B , int /* C */) { } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,20): error CS1001: Identifier expected // public record A(int // A Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(2, 20), // (4,18): error CS1001: Identifier expected // , int /* C */) { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(4, 18), // (4,18): error CS0102: The type 'A' already contains a definition for '' // , int /* C */) { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("A", "").WithLocation(4, 18) ); var ctor = comp.GetMember<NamedTypeSymbol>("A").Constructors[0]; Assert.IsType<ParameterSyntax>(ctor.Parameters[0].DeclaringSyntaxReferences.Single().GetSyntax()); Assert.IsType<ParameterSyntax>(ctor.Parameters[1].DeclaringSyntaxReferences.Single().GetSyntax()); } [Fact, WorkItem(46083, "https://github.com/dotnet/roslyn/issues/46083")] public void IncompletePositionalRecord_SingleParameter() { string source = @" record A(x) "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,10): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // record A(x) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(2, 10), // (2,11): error CS1001: Identifier expected // record A(x) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(2, 11), // (2,12): error CS1514: { expected // record A(x) Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 12), // (2,12): error CS1513: } expected // record A(x) Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 12) ); } [Fact] public void TestWithInExpressionTree() { var source = @" using System; using System.Linq.Expressions; public record C(int i) { public static void M() { Expression<Func<C, C>> expr = c => c with { i = 5 }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,44): error CS8849: An expression tree may not contain a with-expression. // Expression<Func<C, C>> expr = c => c with { i = 5 }; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsWithExpression, "c with { i = 5 }").WithLocation(8, 44) ); } [Fact] public void PartialRecord_MixedWithClass() { var src = @" partial record C(int X, int Y) { } partial class C { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,15): error CS0261: Partial declarations of 'C' must be all classes, all record classes, all structs, all record structs, or all interfaces // partial class C Diagnostic(ErrorCode.ERR_PartialTypeKindConflict, "C").WithArguments("C").WithLocation(5, 15) ); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_ParametersInScopeOfBothParts_RecordClass() { var src = @" var c = new C(2); System.Console.Write((c.P1, c.P2)); public partial record C(int X) { public int P1 { get; set; } = X; } public partial record class C { public int P2 { get; set; } = X; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular10); CompileAndVerify(comp, expectedOutput: "(2, 2)", verify: Verification.Skipped /* init-only */).VerifyDiagnostics(); } [Fact] public void PartialRecord_DuplicateMemberNames() { var src = @" public partial record C(int X) { public void M(int i) { } } public partial record C { public void M(string s) { } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }); var expectedMemberNames = new string[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "M", "M", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordInsideGenericType() { var src = @" var c = new C<int>.Nested(2); System.Console.Write(c.T); public class C<T> { public record Nested(T T); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "2", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordProperties_01() { var src = @" using System; record C(int X, int Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: call ""object..ctor()"" IL_001c: ret } "); var c = verifier.Compilation.GlobalNamespace.GetTypeMember("C"); var x = (IPropertySymbol)c.GetMember("X"); Assert.Equal("System.Int32 C.X.get", x.GetMethod.ToTestDisplayString()); Assert.Equal("void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", x.SetMethod.ToTestDisplayString()); Assert.True(x.SetMethod!.IsInitOnly); var xBackingField = (IFieldSymbol)c.GetMember("<X>k__BackingField"); Assert.Equal("System.Int32 C.<X>k__BackingField", xBackingField.ToTestDisplayString()); Assert.True(xBackingField.IsReadOnly); } [Fact] public void RecordProperties_02() { var src = @" using System; record C(int X, int Y) { public C(int a, int b) { } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } private int X1 = X; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,12): error CS0111: Type 'C' already defines a member called 'C' with the same parameter types // public C(int a, int b) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "C").WithArguments("C", "C").WithLocation(5, 12), // (5,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public C(int a, int b) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C").WithLocation(5, 12), // (11,21): error CS0121: The call is ambiguous between the following methods or properties: 'C.C(int, int)' and 'C.C(int, int)' // var c = new C(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "C").WithArguments("C.C(int, int)", "C.C(int, int)").WithLocation(11, 21) ); } [Fact] public void RecordProperties_03() { var src = @" using System; record C(int X, int Y) { public int X { get; } public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 0 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact] public void RecordProperties_04() { var src = @" using System; record C(int X, int Y) { public int X { get; } = 3; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.X); Console.WriteLine(c.Y); } }"; CompileAndVerify(src, expectedOutput: @" 3 2").VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void RecordProperties_05() { var src = @" record C(int X, int X) { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,21): error CS0100: The parameter name 'X' is a duplicate // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 21), // (2,21): error CS0102: The type 'C' already contains a definition for 'X' // record C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 21) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_05_RecordClass() { var src = @" record class C(int X, int X) { }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (2,27): error CS0100: The parameter name 'X' is a duplicate // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateParamName, "X").WithArguments("X").WithLocation(2, 27), // (2,27): error CS0102: The type 'C' already contains a definition for 'X' // record class C(int X, int X) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(2, 27) ); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.X { get; init; }" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<PropertySymbol>().ToTestDisplayStrings()); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "<X>k__BackingField", "get_X", "set_X", "X", "<X>k__BackingField", "get_X", "set_X", "X", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, comp.GetMember<NamedTypeSymbol>("C").GetPublicSymbol().MemberNames); } [Fact] public void RecordProperties_06() { var src = @" record C(int X, int Y) { public void get_X() { } public void set_X() { } int get_Y(int value) => value; int set_Y(int value) => value; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,14): error CS0082: Type 'C' already reserves a member called 'get_X' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "X").WithArguments("get_X", "C").WithLocation(2, 14), // (2,21): error CS0082: Type 'C' already reserves a member called 'set_Y' with the same parameter types // record C(int X, int Y) Diagnostic(ErrorCode.ERR_MemberReserved, "Y").WithArguments("set_Y", "C").WithLocation(2, 21)); var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.<X>k__BackingField", "System.Int32 C.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.X.init", "System.Int32 C.X { get; init; }", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.Y.init", "System.Int32 C.Y { get; init; }", "void C.get_X()", "void C.set_X()", "System.Int32 C.get_Y(System.Int32 value)", "System.Int32 C.set_Y(System.Int32 value)", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void RecordProperties_07() { var comp = CreateCompilation(@" record C1(object P, object get_P); record C2(object get_P, object P);"); comp.VerifyDiagnostics( // (2,18): error CS0102: The type 'C1' already contains a definition for 'get_P' // record C1(object P, object get_P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C1", "get_P").WithLocation(2, 18), // (3,32): error CS0102: The type 'C2' already contains a definition for 'get_P' // record C2(object get_P, object P); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C2", "get_P").WithLocation(3, 32) ); } [Fact] public void RecordProperties_08() { var comp = CreateCompilation(@" record C1(object O1) { public object O1 { get; } = O1; public object O2 { get; } = O1; }"); comp.VerifyDiagnostics(); } [Fact] public void RecordProperties_09() { var src = @"record C(object P1, object P2, object P3, object P4) { class P1 { } object P2 = 2; int P3(object o) => 3; int P4<T>(T t) => 4; }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (1,17): error CS0102: The type 'C' already contains a definition for 'P1' // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P1").WithArguments("C", "P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (5,9): error CS0102: The type 'C' already contains a definition for 'P3' // int P3(object o) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P3").WithArguments("C", "P3").WithLocation(5, 9), // (6,9): error CS0102: The type 'C' already contains a definition for 'P4' // int P4<T>(T t) => 4; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P4").WithArguments("C", "P4").WithLocation(6, 9) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes() { var src = @" class C<T> { } static class C2 { } ref struct RefLike{} unsafe record C( // 1 int* P1, // 2 int*[] P2, // 3 C<int*[]> P3, delegate*<int, int> P4, // 4 void P5, // 5 C2 P6, // 6, 7 System.ArgIterator P7, // 8 System.TypedReference P8, // 9 RefLike P9); // 10 "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (6,15): error CS0721: 'C2': static types cannot be used as parameters // unsafe record C( // 1 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "C").WithArguments("C2").WithLocation(6, 15), // (7,10): error CS8908: The type 'int*' may not be used for a field of a record. // int* P1, // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P1").WithArguments("int*").WithLocation(7, 10), // (8,12): error CS8908: The type 'int*[]' may not be used for a field of a record. // int*[] P2, // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P2").WithArguments("int*[]").WithLocation(8, 12), // (10,25): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // delegate*<int, int> P4, // 4 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "P4").WithArguments("delegate*<int, int>").WithLocation(10, 25), // (11,5): error CS1536: Invalid parameter type 'void' // void P5, // 5 Diagnostic(ErrorCode.ERR_NoVoidParameter, "void").WithLocation(11, 5), // (12,8): error CS0722: 'C2': static types cannot be used as return types // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (12,8): error CS0721: 'C2': static types cannot be used as parameters // C2 P6, // 6, 7 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "P6").WithArguments("C2").WithLocation(12, 8), // (13,5): error CS0610: Field or property cannot be of type 'ArgIterator' // System.ArgIterator P7, // 8 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 5), // (14,5): error CS0610: Field or property cannot be of type 'TypedReference' // System.TypedReference P8, // 9 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 5), // (15,5): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // RefLike P9); // 10 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 5) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1; // 1 public int*[] f2; // 2 public C<int*[]> f3; public delegate*<int, int> f4; // 3 public void f5; // 4 public C2 f6; // 5 public System.ArgIterator f7; // 6 public System.TypedReference f8; // 7 public RefLike f9; // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1; // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2; // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4; // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,12): error CS0670: Field cannot have void type // public void f5; // 4 Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void").WithLocation(12, 12), // (13,15): error CS0723: Cannot declare a variable of static type 'C2' // public C2 f6; // 5 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(13, 15), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7; // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8; // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9; // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_NominalMembers_AutoProperties() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public int* f1 { get; set; } // 1 public int*[] f2 { get; set; } // 2 public C<int*[]> f3 { get; set; } public delegate*<int, int> f4 { get; set; } // 3 public void f5 { get; set; } // 4 public C2 f6 { get; set; } // 5, 6 public System.ArgIterator f7 { get; set; } // 6 public System.TypedReference f8 { get; set; } // 7 public RefLike f9 { get; set; } // 8 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (8,17): error CS8908: The type 'int*' may not be used for a field of a record. // public int* f1 { get; set; } // 1 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f1").WithArguments("int*").WithLocation(8, 17), // (9,19): error CS8908: The type 'int*[]' may not be used for a field of a record. // public int*[] f2 { get; set; } // 2 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f2").WithArguments("int*[]").WithLocation(9, 19), // (11,32): error CS8908: The type 'delegate*<int, int>' may not be used for a field of a record. // public delegate*<int, int> f4 { get; set; } // 3 Diagnostic(ErrorCode.ERR_BadFieldTypeInRecord, "f4").WithArguments("delegate*<int, int>").WithLocation(11, 32), // (12,17): error CS0547: 'C.f5': property or indexer cannot have void type // public void f5 { get; set; } // 4 Diagnostic(ErrorCode.ERR_PropertyCantHaveVoidType, "f5").WithArguments("C.f5").WithLocation(12, 17), // (13,20): error CS0722: 'C2': static types cannot be used as return types // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("C2").WithLocation(13, 20), // (13,25): error CS0721: 'C2': static types cannot be used as parameters // public C2 f6 { get; set; } // 5, 6 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("C2").WithLocation(13, 25), // (14,12): error CS0610: Field or property cannot be of type 'ArgIterator' // public System.ArgIterator f7 { get; set; } // 6 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(14, 12), // (15,12): error CS0610: Field or property cannot be of type 'TypedReference' // public System.TypedReference f8 { get; set; } // 7 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(15, 12), // (16,12): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public RefLike f9 { get; set; } // 8 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(16, 12) ); } [Fact] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_PointerTypeAllowedForParameterAndProperty() { var src = @" class C<T> { } unsafe record C(int* P1, int*[] P2, C<int*[]> P3) { int* P1 { get { System.Console.Write(""P1 ""); return null; } init { } } int*[] P2 { get { System.Console.Write(""P2 ""); return null; } init { } } C<int*[]> P3 { get { System.Console.Write(""P3 ""); return null; } init { } } public unsafe static void Main() { var x = new C(null, null, null); var (x1, x2, x3) = x; System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugExe); comp.VerifyEmitDiagnostics( // (4,22): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(4, 22), // (4,33): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(4, 33), // (4,47): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // unsafe record C(int* P1, int*[] P2, C<int*[]> P3) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(4, 47) ); CompileAndVerify(comp, expectedOutput: "P1 P2 P3 RAN", verify: Verification.Skipped /* pointers */); } [ConditionalFact(typeof(DesktopOnly), Reason = ConditionalSkipReason.RestrictedTypesNeedDesktop)] [WorkItem(48115, "https://github.com/dotnet/roslyn/issues/48115")] public void RestrictedTypesAndPointerTypes_StaticFields() { var src = @" public class C<T> { } public static class C2 { } public ref struct RefLike{} public unsafe record C { public static int* f1; public static int*[] f2; public static C<int*[]> f3; public static delegate*<int, int> f4; public static C2 f6; // 1 public static System.ArgIterator f7; // 2 public static System.TypedReference f8; // 3 public static RefLike f9; // 4 } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.UnsafeDebugDll); comp.VerifyEmitDiagnostics( // (12,22): error CS0723: Cannot declare a variable of static type 'C2' // public static C2 f6; // 1 Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "f6").WithArguments("C2").WithLocation(12, 22), // (13,19): error CS0610: Field or property cannot be of type 'ArgIterator' // public static System.ArgIterator f7; // 2 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(13, 19), // (14,19): error CS0610: Field or property cannot be of type 'TypedReference' // public static System.TypedReference f8; // 3 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(14, 19), // (15,19): error CS8345: Field or auto-implemented property cannot be of type 'RefLike' unless it is an instance member of a ref struct. // public static RefLike f9; // 4 Diagnostic(ErrorCode.ERR_FieldAutoPropCantBeByRefLike, "RefLike").WithArguments("RefLike").WithLocation(15, 19) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1, 2 { public object O1 { get; init; } public object O2 { get; init; } = M(O2); public object O3 { get; init; } = M(O3 = null); private static object M(object o) => o; } record Base(object O); record C2(object O4) : Base(O4) // we didn't complain because the parameter is read { public object O4 { get; init; } } record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 { public object O5 { get; init; } } record C4(object O6) : Base((System.Func<object, object>)(_ => O6)) { public object O6 { get; init; } } record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 { public object O7 { get; init; } } "); comp.VerifyDiagnostics( // (2,18): warning CS8907: Parameter 'O1' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O1").WithArguments("O1").WithLocation(2, 18), // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1, 2 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40), // (16,18): warning CS8907: Parameter 'O5' is unread. Did you forget to use it to initialize the property with that name? // record C3(object O5) : Base((System.Func<object, object>)(x => x)) // 3 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O5").WithArguments("O5").WithLocation(16, 18), // (26,18): warning CS8907: Parameter 'O7' is unread. Did you forget to use it to initialize the property with that name? // record C5(object O7) : Base((System.Func<object, object>)(_ => (O7 = 42) )) // 4 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O7").WithArguments("O7").WithLocation(26, 18) ); } [Fact, WorkItem(48584, "https://github.com/dotnet/roslyn/issues/48584")] public void RecordProperties_11_UnreadPositionalParameter_InRefOut() { var comp = CreateCompilation(@" record C1(object O1, object O2, object O3) // 1 { public object O1 { get; init; } = MIn(in O1); public object O2 { get; init; } = MRef(ref O2); public object O3 { get; init; } = MOut(out O3); static object MIn(in object o) => o; static object MRef(ref object o) => o; static object MOut(out object o) => throw null; } "); comp.VerifyDiagnostics( // (2,40): warning CS8907: Parameter 'O3' is unread. Did you forget to use it to initialize the property with that name? // record C1(object O1, object O2, object O3) // 1 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "O3").WithArguments("O3").WithLocation(2, 40) ); } [Fact] public void EmptyRecord_01() { var src = @" record C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_01_RecordClass() { var src = @" record class C(); class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True", parseOptions: TestOptions.Regular10); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); var comp = (CSharpCompilation)verifier.Compilation; var actualMembers = comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor()", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void EmptyRecord_02() { var src = @" record C() { C(int x) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,5): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // C(int x) Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "C", isSuppressed: false).WithLocation(4, 5) ); } [Fact] public void EmptyRecord_03() { var src = @" record B { public B(int x) { System.Console.WriteLine(x); } } record C() : B(12) { C(int x) : this() {} } class Program { static void Main() { _ = new C(); } } "; var verifier = CompileAndVerify(src, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 12 IL_0003: call ""B..ctor(int)"" IL_0008: ret } "); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor() { var src = @" record R(int x) { static void Main() { } static R() { System.Console.Write(""static ctor""); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); // [ : R::set_x] Cannot change initonly field outside its .ctor. CompileAndVerify(comp, expectedOutput: "static ctor", verify: Verification.Skipped); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_ParameterlessPrimaryCtor() { var src = @" record R() { static R() { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(50170, "https://github.com/dotnet/roslyn/issues/50170")] public void StaticCtor_CopyCtor() { var src = @" record R() { static R(R r) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0132: 'R.R(R)': a static constructor must be parameterless // static R(R r) { } Diagnostic(ErrorCode.ERR_StaticConstParam, "R").WithArguments("R.R(R)").WithLocation(4, 12) ); } [Fact] public void WithExpr1() { var src = @" record C(int X) { public static void Main() { var c = new C(0); _ = Main() with { }; _ = default with { }; _ = null with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = Main() with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "Main()").WithLocation(7, 13), // (8,13): error CS8716: There is no target type for the default literal. // _ = default with { }; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(8, 13), // (9,13): error CS8802: The receiver of a `with` expression must have a valid non-void type. // _ = null with { }; Diagnostic(ErrorCode.ERR_InvalidWithReceiverType, "null").WithLocation(9, 13) ); } [Fact] public void WithExpr2() { var src = @" using System; record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; Console.WriteLine(c1.X); Console.WriteLine(c2.X); } }"; CompileAndVerify(src, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void WithExpr3() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var root = comp.SyntaxTrees[0].GetRoot(); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (2) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { }') Left: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Right: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0) "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr4() { var src = @" class B { public B Clone() => null; } record C(int X) : B { public static void Main() { var c = new C(0); c = c with { }; } public new C Clone() => null; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr6() { var src = @" record B { public int X { get; init; } } record C : B { public static void Main() { var c = new C(); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr7() { var src = @" record B { public int X { get; } } record C : B { public new int X { get; init; } public static void Main() { var c = new C(); B b = c; b = b with { X = 0 }; var b2 = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,22): error CS0200: Property or indexer 'B.X' cannot be assigned to -- it is read only // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "X").WithArguments("B.X").WithLocation(14, 22) ); } [Fact] public void WithExpr8() { var src = @" record B { public int X { get; } } record C : B { public string Y { get; } public static void Main() { var c = new C(); B b = c; b = b with { }; b = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr9() { var src = @" record C(int X) { public string Clone() => null; public static void Main() { var c = new C(0); c = c with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS8859: Members named 'Clone' are disallowed in records. // public string Clone() => null; Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(4, 19) ); } [Fact] public void WithExpr11() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """"}; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = ""}; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExpr12() { var src = @" using System; record C(int X) { public static void Main() { var c = new C(0); Console.WriteLine(c.X); c = c with { X = 5 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 5").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 40 (0x28) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""int C.X.get"" IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0016: dup IL_0017: ldc.i4.5 IL_0018: callvirt ""void C.X.init"" IL_001d: callvirt ""int C.X.get"" IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ret }"); } [Fact] public void WithExpr13() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: call ""void System.Console.WriteLine(object)"" IL_001e: ret }"); } [Fact] public void WithExpr14() { var src = @" using System; record C(int X, int Y) { public override string ToString() => X + "" "" + Y; public static void Main() { var c = new C(0, 1); Console.WriteLine(c); c = c with { X = 5 }; Console.WriteLine(c); c = c with { Y = 2 }; Console.WriteLine(c); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"0 1 5 1 5 2").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 49 (0x31) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""C..ctor(int, int)"" IL_0007: dup IL_0008: call ""void System.Console.WriteLine(object)"" IL_000d: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0012: dup IL_0013: ldc.i4.5 IL_0014: callvirt ""void C.X.init"" IL_0019: dup IL_001a: call ""void System.Console.WriteLine(object)"" IL_001f: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0024: dup IL_0025: ldc.i4.2 IL_0026: callvirt ""void C.Y.init"" IL_002b: call ""void System.Console.WriteLine(object)"" IL_0030: ret }"); } [Fact] public void WithExpr15() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { = 5 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS1525: Invalid expression term '=' // c = c with { = 5 }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(8, 22) ); } [Fact] public void WithExpr16() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { X = }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS1525: Invalid expression term '}' // c = c with { X = }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr17() { var src = @" record B { public int X { get; } private B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr18() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) : B { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The receiver type 'B' does not have an accessible parameterless instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr19() { var src = @" class B { public int X { get; } protected B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8803: The 'with' expression requires the receiver type 'B' to have a single accessible non-inherited instance method named "Clone". // b = b with { }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13) ); } [Fact] public void WithExpr20() { var src = @" using System; record C { public event Action X; public static void Main() { var c = new C(); c = c with { X = null }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,25): warning CS0067: The event 'C.X' is never used // public event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(5, 25) ); } [Fact] public void WithExpr21() { var src = @" record B { public class X { } } class C { public static void Main() { var b = new B(); b = b with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0572: 'X': cannot reference a type through an expression; try 'B.X' instead // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_BadTypeReference, "X").WithArguments("X", "B.X").WithLocation(11, 22), // (11,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // b = b with { X = 0 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(11, 22) ); } [Fact] public void WithExpr22() { var src = @" record B { public int X = 0; } class C { public static void Main() { var b = new B(); b = b with { }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr23() { var src = @" class B { public int X = 0; public B Clone() => null; } record C(int X) { public static void Main() { var b = new B(); b = b with { Y = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,13): error CS8858: The receiver type 'B' is not a valid record type. // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "b").WithArguments("B").WithLocation(12, 13), // (12,22): error CS0117: 'B' does not contain a definition for 'Y' // b = b with { Y = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Y").WithArguments("B", "Y").WithLocation(12, 22) ); } [Fact] public void WithExpr24_Dynamic() { var src = @" record C(int X) { public static void Main() { dynamic c = new C(1); var x = c with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,17): error CS8858: The receiver type 'dynamic' is not a valid record type. // var x = c with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("dynamic").WithLocation(7, 17) ); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr25_TypeParameterWithRecordConstraint() { var src = @" record R(int X); class C { public static T M<T>(T t) where T : R { return t with { X = 2 }; } static void Main() { System.Console.Write(M(new R(-1)).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "2").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 29 (0x1d) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.init"" IL_001c: ret } "); } [Fact, WorkItem(46427, "https://github.com/dotnet/roslyn/issues/46427"), WorkItem(46249, "https://github.com/dotnet/roslyn/issues/46249")] public void WithExpr26_TypeParameterWithRecordAndInterfaceConstraint() { var src = @" record R { public int X { get; set; } } interface I { int Property { get; set; } } record T : R, I { public int Property { get; set; } } class C { public static T M<T>(T t) where T : R, I { return t with { X = 2, Property = 3 }; } static void Main() { System.Console.WriteLine(M(new T()).X); System.Console.WriteLine(M(new T()).Property); } }"; var verifier = CompileAndVerify( new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, verify: Verification.Passes, expectedOutput: @"2 3").VerifyDiagnostics(); verifier.VerifyIL("C.M<T>(T)", @" { // Code size 41 (0x29) .maxstack 3 IL_0000: ldarg.0 IL_0001: box ""T"" IL_0006: callvirt ""R R.<Clone>$()"" IL_000b: unbox.any ""T"" IL_0010: dup IL_0011: box ""T"" IL_0016: ldc.i4.2 IL_0017: callvirt ""void R.X.set"" IL_001c: dup IL_001d: box ""T"" IL_0022: ldc.i4.3 IL_0023: callvirt ""void I.Property.set"" IL_0028: ret } "); } [Fact] public void WithExpr27_InExceptionFilter() { var src = @" var r = new R(1); try { throw new System.Exception(); } catch (System.Exception) when ((r = r with { X = 2 }).X == 2) { System.Console.Write(""RAN ""); System.Console.Write(r.X); } record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN 2", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr28_WithAwait() { var src = @" var r = new R(1); r = r with { X = await System.Threading.Tasks.Task.FromResult(42) }; System.Console.Write(r.X); record R(int X); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var x = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Last().Left; Assert.Equal("X", x.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal("System.Int32 R.X { get; init; }", symbol.ToTestDisplayString()); } [Fact, WorkItem(46465, "https://github.com/dotnet/roslyn/issues/46465")] public void WithExpr29_DisallowedAsExpressionStatement() { var src = @" record R(int X) { void M() { var r = new R(1); r with { X = 2 }; } } "; // Note: we didn't parse the `with` as a `with` expression, but as a broken local declaration // Tracked by https://github.com/dotnet/roslyn/issues/46465 var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (7,9): error CS0118: 'r' is a variable but is used like a type // r with { X = 2 }; Diagnostic(ErrorCode.ERR_BadSKknown, "r").WithArguments("r", "variable", "type").WithLocation(7, 9), // (7,11): warning CS0168: The variable 'with' is declared but never used // r with { X = 2 }; Diagnostic(ErrorCode.WRN_UnreferencedVar, "with").WithArguments("with").WithLocation(7, 11), // (7,16): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(7, 16), // (7,18): error CS8852: Init-only property or indexer 'R.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor. // r with { X = 2 }; Diagnostic(ErrorCode.ERR_AssignmentInitOnly, "X").WithArguments("R.X").WithLocation(7, 18), // (7,24): error CS1002: ; expected // r with { X = 2 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 24) ); } [Fact] public void WithExpr30_TypeParameterNoConstraint() { var src = @" class C { public static void M<T>(T t) { _ = t with { X = 2 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr31_TypeParameterWithInterfaceConstraint() { var src = @" interface I { int Property { get; set; } } class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(8, 13), // (8,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(8, 22) ); } [Fact] public void WithExpr32_TypeParameterWithInterfaceConstraint() { var ilSource = @" .class interface public auto ansi abstract I { // Methods .method public hidebysig specialname newslot abstract virtual instance class I '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { } // end of method I::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot abstract virtual instance int32 get_Property () cil managed { } // end of method I::get_Property .method public hidebysig specialname newslot abstract virtual instance void set_Property ( int32 'value' ) cil managed { } // end of method I::set_Property // Properties .property instance int32 Property() { .get instance int32 I::get_Property() .set instance void I::set_Property(int32) } } // end of class I "; var src = @" class C { public static void M<T>(T t) where T : I { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,13): error CS8858: The receiver type 'T' is not a valid record type. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_CannotClone, "t").WithArguments("T").WithLocation(6, 13), // (6,22): error CS0117: 'T' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("T", "X").WithLocation(6, 22) ); } [Fact] public void WithExpr33_TypeParameterWithStructureConstraint() { var ilSource = @" .class public sequential ansi sealed beforefieldinit S extends System.ValueType { .pack 0 .size 1 // Methods .method public hidebysig instance valuetype S '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { // Method begins at RVA 0x2150 // Code size 2 (0x2) .maxstack 1 .locals init ( [0] valuetype S ) IL_0000: ldnull IL_0001: throw } // end of method S::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname instance int32 get_Property () cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::get_Property .method public hidebysig specialname instance void set_Property ( int32 'value' ) cil managed { // Method begins at RVA 0x215e // Code size 2 (0x2) .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method S::set_Property // Properties .property instance int32 Property() { .get instance int32 S::get_Property() .set instance void S::set_Property(int32) } } // end of class S "; var src = @" abstract class Base<T> { public abstract void M<U>(U t) where U : T; } class C : Base<S> { public override void M<U>(U t) { _ = t with { X = 2, Property = 3 }; } }"; var comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8773: Feature 'with on structs' is not available in C# 9.0. Please use language version 10.0 or greater. // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "t with { X = 2, Property = 3 }").WithArguments("with on structs", "10.0").WithLocation(11, 13), // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); comp = CreateCompilationWithIL(new[] { src, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (11,22): error CS0117: 'U' does not contain a definition for 'X' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("U", "X").WithLocation(11, 22), // (11,29): error CS0117: 'U' does not contain a definition for 'Property' // _ = t with { X = 2, Property = 3 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "Property").WithArguments("U", "Property").WithLocation(11, 29) ); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreDefined() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void BothGetHashCodeAndEqualsAreNotDefined() { var src = @" public sealed record C { public object Data; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void GetHashCodeIsDefinedButEqualsIsNot() { var src = @" public sealed record C { public object Data; public override int GetHashCode() { return 0; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47513, "https://github.com/dotnet/roslyn/issues/47513")] public void EqualsIsDefinedButGetHashCodeIsNot() { var src = @" public sealed record C { public object Data; public bool Equals(C c) { return false; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (5,17): warning CS8851: 'C' defines 'Equals' but not 'GetHashCode' // public bool Equals(C c) { return false; } Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("C").WithLocation(5, 17)); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord() { var src = @" class record { } class C { record M(record r) => r; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,7): error CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7), // (6,24): error CS1514: { expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_LbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1513: } expected // record M(record r) => r; Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 24), // (6,24): error CS1519: Invalid token '=>' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "=>").WithArguments("=>").WithLocation(6, 24), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28), // (6,28): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // record M(record r) => r; Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";").WithLocation(6, 28) ); comp = CreateCompilation(src, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Struct() { var src = @" struct record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // struct record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Interface() { var src = @" interface record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,11): warning CS8860: Types and aliases should not be named 'record'. // interface record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 11) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Enum() { var src = @" enum record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,6): warning CS8860: Types and aliases should not be named 'record'. // enum record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 6) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate() { var src = @" delegate void record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // delegate void record(); Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Delegate_Escaped() { var src = @" delegate void @record(); "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias() { var src = @" using record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using record = System.Console;").WithLocation(2, 1), // (2,7): warning CS8860: Types and aliases should not be named 'record'. // using record = System.Console; Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Alias_Escaped() { var src = @" using @record = System.Console; "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,1): hidden CS8019: Unnecessary using directive. // using @record = System.Console; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using @record = System.Console;").WithLocation(2, 1) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter() { var src = @" class C<record> { } // 1 class C2 { class Nested<record> { } // 2 } class C3 { void Method<record>() { } // 3 void Method2() { void local<record>() // 4 { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,9): warning CS8860: Types and aliases should not be named 'record'. // class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 9), // (5,18): warning CS8860: Types and aliases should not be named 'record'. // class Nested<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 18), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // void Method<record>() { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (13,20): warning CS8860: Types and aliases should not be named 'record'. // void local<record>() // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(13, 20) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped() { var src = @" class C<@record> { } class C2 { class Nested<@record> { } } class C3 { void Method<@record>() { } void Method2() { void local<@record>() { local<record>(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TypeParameter_Escaped_Partial() { var src = @" partial class C<@record> { } partial class C<record> { } // 1 partial class D<record> { } // 2 partial class D<@record> { } partial class D<record> { } // 3 partial class D<record> { } // 4 partial class E<@record> { } partial class E<@record> { } partial class C2 { partial class Nested<record> { } // 5 partial class Nested<@record> { } } partial class C3 { partial void Method<@record>(); partial void Method<record>() { } // 6 partial void Method2<@record>() { } partial void Method2<record>(); // 7 partial void Method3<record>(); // 8 partial void Method3<@record>() { } partial void Method4<record>() { } // 9 partial void Method4<@record>(); } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,17): warning CS8860: Types and aliases should not be named 'record'. // partial class C<record> { } // 1 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 17), // (5,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 2 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(5, 17), // (8,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 3 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(8, 17), // (9,17): warning CS8860: Types and aliases should not be named 'record'. // partial class D<record> { } // 4 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(9, 17), // (16,26): warning CS8860: Types and aliases should not be named 'record'. // partial class Nested<record> { } // 5 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(16, 26), // (22,25): warning CS8860: Types and aliases should not be named 'record'. // partial void Method<record>() { } // 6 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(22, 25), // (25,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method2<record>(); // 7 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(25, 26), // (27,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method3<record>(); // 8 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(27, 26), // (30,26): warning CS8860: Types and aliases should not be named 'record'. // partial void Method4<record>() { } // 9 Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(30, 26) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Record() { var src = @" record record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,8): warning CS8860: Types and aliases should not be named 'record'. // record record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 8) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_TwoParts() { var src = @" partial class record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15), // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_Escaped() { var src = @" class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial() { var src = @" partial class @record { } partial class record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (3,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(3, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_MixedEscapedPartial_ReversedOrder() { var src = @" partial class record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,15): warning CS8860: Types and aliases should not be named 'record'. // partial class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 15) ); } [Fact, WorkItem(47090, "https://github.com/dotnet/roslyn/issues/47090")] public void TypeNamedRecord_BothEscapedPartial() { var src = @" partial class @record { } partial class @record { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void TypeNamedRecord_EscapedReturnType() { var src = @" class record { } class C { @record M(record r) { System.Console.Write(""RAN""); return r; } public static void Main() { var c = new C(); _ = c.M(new record()); } }"; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (2,7): warning CS8860: Types and aliases should not be named 'record'. // class record { } Diagnostic(ErrorCode.WRN_RecordNamedDisallowed, "record").WithArguments("record").WithLocation(2, 7) ); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact, WorkItem(45591, "https://github.com/dotnet/roslyn/issues/45591")] public void Clone_DisallowedInSource() { var src = @" record C1(string Clone); // 1 record C2 { string Clone; // 2 } record C3 { string Clone { get; set; } // 3 } record C4 { data string Clone; // 4 not yet supported } record C5 { void Clone() { } // 5 void Clone(int i) { } // 6 } record C6 { class Clone { } // 7 } record C7 { delegate void Clone(); // 8 } record C8 { event System.Action Clone; // 9 } record Clone { Clone(int i) => throw null; } record C9 : System.ICloneable { object System.ICloneable.Clone() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (2,18): error CS8859: Members named 'Clone' are disallowed in records. // record C1(string Clone); // 1 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(2, 18), // (5,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone; // 2 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(5, 12), // (5,12): warning CS0169: The field 'C2.Clone' is never used // string Clone; // 2 Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C2.Clone").WithLocation(5, 12), // (9,12): error CS8859: Members named 'Clone' are disallowed in records. // string Clone { get; set; } // 3 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(9, 12), // (13,10): error CS1519: Invalid token 'string' in class, record, struct, or interface member declaration // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "string").WithArguments("string").WithLocation(13, 10), // (13,17): error CS8859: Members named 'Clone' are disallowed in records. // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(13, 17), // (13,17): warning CS0169: The field 'C4.Clone' is never used // data string Clone; // 4 not yet supported Diagnostic(ErrorCode.WRN_UnreferencedField, "Clone").WithArguments("C4.Clone").WithLocation(13, 17), // (17,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone() { } // 5 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(17, 10), // (18,10): error CS8859: Members named 'Clone' are disallowed in records. // void Clone(int i) { } // 6 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(18, 10), // (22,11): error CS8859: Members named 'Clone' are disallowed in records. // class Clone { } // 7 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(22, 11), // (26,19): error CS8859: Members named 'Clone' are disallowed in records. // delegate void Clone(); // 8 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(26, 19), // (30,25): error CS8859: Members named 'Clone' are disallowed in records. // event System.Action Clone; // 9 Diagnostic(ErrorCode.ERR_CloneDisallowedInRecord, "Clone").WithLocation(30, 25), // (30,25): warning CS0067: The event 'C8.Clone' is never used // event System.Action Clone; // 9 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Clone").WithArguments("C8.Clone").WithLocation(30, 25) ); } [Fact] public void Clone_LoadedFromMetadata() { // IL for ' public record Base(int i);' with a 'void Clone()' method added var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .field private initonly int32 '<i>k__BackingField' .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname newslot virtual instance class Base '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void Base::.ctor(class Base) IL_0006: ret } .method family hidebysig specialname newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldtoken Base IL_0005: call class [mscorlib]System.Type [mscorlib]System.Type::GetTypeFromHandle(valuetype [mscorlib]System.RuntimeTypeHandle) IL_000a: ret } .method public hidebysig specialname rtspecialname instance void .ctor ( int32 i ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ldarg.0 IL_0008: call instance void [mscorlib]System.Object::.ctor() IL_000d: ret } .method public hidebysig specialname instance int32 get_i () cil managed { IL_0000: ldarg.0 IL_0001: ldfld int32 Base::'<i>k__BackingField' IL_0006: ret } .method public hidebysig specialname instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_i ( int32 'value' ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld int32 Base::'<i>k__BackingField' IL_0007: ret } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::get_Default() IL_0005: ldarg.0 IL_0006: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000b: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<class [mscorlib]System.Type>::GetHashCode(!0) IL_0010: ldc.i4 -1521134295 IL_0015: mul IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: callvirt instance int32 class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::GetHashCode(!0) IL_0026: add IL_0027: ret } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst Base IL_0007: callvirt instance bool Base::Equals(class Base) IL_000c: ret } .method public newslot virtual instance bool Equals ( class Base '' ) cil managed { IL_0000: ldarg.1 IL_0001: brfalse.s IL_002d IL_0003: ldarg.0 IL_0004: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_0009: ldarg.1 IL_000a: callvirt instance class [mscorlib]System.Type Base::get_EqualityContract() IL_000f: call bool [mscorlib]System.Type::op_Equality(class [mscorlib]System.Type, class [mscorlib]System.Type) IL_0014: brfalse.s IL_002d IL_0016: call class [mscorlib]System.Collections.Generic.EqualityComparer`1<!0> class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::get_Default() IL_001b: ldarg.0 IL_001c: ldfld int32 Base::'<i>k__BackingField' IL_0021: ldarg.1 IL_0022: ldfld int32 Base::'<i>k__BackingField' IL_0027: callvirt instance bool class [mscorlib]System.Collections.Generic.EqualityComparer`1<int32>::Equals(!0, !0) IL_002c: ret IL_002d: ldc.i4.0 IL_002e: ret } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base '' ) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld int32 Base::'<i>k__BackingField' IL_000d: stfld int32 Base::'<i>k__BackingField' IL_0012: ret } .method public hidebysig instance void Deconstruct ( [out] int32& i ) cil managed { IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call instance int32 Base::get_i() IL_0007: stind.i4 IL_0008: ret } .method public hidebysig instance void Clone () cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::Write(string) IL_000a: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type Base::get_EqualityContract() } .property instance int32 i() { .get instance int32 Base::get_i() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) Base::set_i(int32) } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi abstract sealed beforefieldinit System.Runtime.CompilerServices.IsExternalInit extends [mscorlib]System.Object { } "; var src = @" record R(int i) : Base(i); public class C { public static void Main() { var r = new R(1); r.Clone(); } } "; var comp = CreateCompilationWithIL(src, il, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); // Note: we do load the Clone method from metadata } [Fact] public void Clone_01() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_02() { var src = @" sealed abstract record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // sealed abstract record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var clone = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_03() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); } [Fact] public void Clone_04() { var src = @" record C1; sealed abstract record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // sealed abstract record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var clone = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); Assert.True(clone.ContainingType.IsSealed); Assert.True(clone.ContainingType.IsAbstract); var namedTypeSymbol = comp.GlobalNamespace.GetTypeMember("C1"); Assert.True(namedTypeSymbol.IsRecord); Assert.Equal("record C1", namedTypeSymbol .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_05_IntReturnType_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_06_IntReturnType_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_07_Ambiguous_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_08_Ambiguous_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_09_AmbiguousReverseOrder_UsedAsBaseType() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_10_AmbiguousReverseOrder_UsedInWith() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig specialname newslot virtual instance int32 '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A "; var source = @" public class Program { static void Main() { A x = new A() with { }; } } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (6,15): error CS8858: The receiver type 'A' is not a valid record type. // A x = new A() with { }; Diagnostic(ErrorCode.ERR_CannotClone, "new A()").WithArguments("A").WithLocation(6, 15) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_11() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_12() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_12", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" class Program { public static void Main() { var c1 = new B(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_12, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18) ); } [Fact] public void Clone_13() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_13", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" class Program { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (7,18): error CS8858: The receiver type 'C' is not a valid record type. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c1").WithArguments("C").WithLocation(7, 18), // (7,18): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (7,28): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "X").WithArguments("B", "Clone_13, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 28), // (7,28): error CS0117: 'C' does not contain a definition for 'X' // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("C", "X").WithLocation(7, 28) ); } [Fact] public void Clone_14() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(source1).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; CompileAndVerify(source3, references: new[] { comp1Ref, comp2Ref }, expectedOutput: @"1 11").VerifyDiagnostics(); } [Fact] public void Clone_15() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, assemblyName: "Clone_15", parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" record C(int X) : B(X) { public static void Main() { var c1 = new C(1); var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } } "; var comp3 = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp2Ref }, parseOptions: TestOptions.Regular9); comp3.VerifyEmitDiagnostics( // (2,8): error CS8869: 'C.Equals(object?)' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'C.GetHashCode()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'C.ToString()' does not override expected method from 'object'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 8), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record C(int X) : B(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new C(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22), // (7,18): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c2 = c1 with { X = 11 }; Diagnostic(ErrorCode.ERR_NoTypeDef, "c1").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18), // (8,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c1.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 9), // (9,9): error CS0012: The type 'A' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(c2.X); Diagnostic(ErrorCode.ERR_NoTypeDef, "System").WithArguments("A", "Clone_15, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(9, 9) ); } [Fact] public void Clone_16() { string source1 = @" public record A; "; var comp1Ref = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source2 = @" public record B(int X) : A; "; var comp2Ref = CreateCompilation(new[] { source2, IsExternalInitTypeDefinition }, assemblyName: "Clone_16", references: new[] { comp1Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source3 = @" public record C(int X) : B(X); "; var comp3Ref = CreateCompilation(new[] { source3, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp2Ref }, parseOptions: TestOptions.Regular9).EmitToImageReference(); string source4 = @" record D(int X) : C(X) { public static void Main() { var c1 = new D(1); var c2 = c1 with { X = 11 }; } } "; var comp4 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp1Ref, comp3Ref }, parseOptions: TestOptions.Regular9); comp4.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); var comp5 = CreateCompilation(new[] { source4, IsExternalInitTypeDefinition }, references: new[] { comp3Ref }, parseOptions: TestOptions.Regular9); comp5.VerifyEmitDiagnostics( // (2,8): error CS8869: 'D.Equals(object?)' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.Equals(object?)").WithLocation(2, 8), // (2,8): error CS8869: 'D.GetHashCode()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.GetHashCode()").WithLocation(2, 8), // (2,8): error CS8869: 'D.ToString()' does not override expected method from 'object'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "D").WithArguments("D.ToString()").WithLocation(2, 8), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (2,19): error CS8864: Records may only inherit from object or another record // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_BadRecordBase, "C").WithLocation(2, 19), // (2,19): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // record D(int X) : C(X) Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 19), // (6,22): error CS0012: The type 'B' is defined in an assembly that is not referenced. You must add a reference to assembly 'Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var c1 = new D(1); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("B", "Clone_16, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(6, 22) ); } [Fact] public void Clone_17_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_18_NonOverridable() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool PrintMembers ( class [mscorlib]System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,19): error CS8864: Records may only inherit from object or another record // public record B : A { Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(2, 19) ); Assert.Equal("class A", comp.GlobalNamespace.GetTypeMember("A") .ToDisplayString(SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void Clone_19() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname virtual final instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'C.<Clone>$()': cannot override inherited member 'B.<Clone>$()' because it is sealed // public record C : B { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.<Clone>$()", "B.<Clone>$()").WithLocation(2, 15) ); } [Fact, WorkItem(47093, "https://github.com/dotnet/roslyn/issues/47093")] public void ToString_TopLevelRecord_Empty() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); abstract record C1; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool C1.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractRecord() { var src = @" var c2 = new C2(); System.Console.Write(c2); record Base; abstract record C1 : Base; record C2 : C1 { public override string ToString() => base.ToString(); } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: ret } "); v.VerifyIL("C1." + WellKnownMemberNames.ObjectToString, @" { // Code size 64 (0x40) .maxstack 2 .locals init (System.Text.StringBuilder V_0) IL_0000: newobj ""System.Text.StringBuilder..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: ldstr ""C1"" IL_000c: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0011: pop IL_0012: ldloc.0 IL_0013: ldstr "" { "" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_001d: pop IL_001e: ldarg.0 IL_001f: ldloc.0 IL_0020: callvirt ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0025: brfalse.s IL_0030 IL_0027: ldloc.0 IL_0028: ldc.i4.s 32 IL_002a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_002f: pop IL_0030: ldloc.0 IL_0031: ldc.i4.s 125 IL_0033: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(char)"" IL_0038: pop IL_0039: ldloc.0 IL_003a: callvirt ""string object.ToString()"" IL_003f: ret } "); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilder() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeTypeMissing(WellKnownType.System_Text_StringBuilder); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "record C1;").WithArguments("System.Text.StringBuilder").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Text.StringBuilder' is not defined or imported // record C1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "C1").WithArguments("System.Text.StringBuilder").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderCtor() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__ctor); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder..ctor' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", ".ctor").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_MissingStringBuilderAppendString() { var src = @" record C1; "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1;").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendString() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_OneProperty_MissingStringBuilderAppendStringAndChar() { var src = @" record C1(int P); "; var comp = CreateCompilation(src); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendString); comp.MakeMemberMissing(WellKnownMember.System_Text_StringBuilder__AppendChar); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Text.StringBuilder.Append' // record C1(int P); Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C1(int P);").WithArguments("System.Text.StringBuilder", "Append").WithLocation(2, 1) ); } [Fact] public void ToString_TopLevelRecord_Empty_Sealed() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); sealed record C1; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact] public void ToString_AbstractRecord() { var src = @" var c2 = new C2(42, 43); System.Console.Write(c2.ToString()); abstract record C1(int I1); sealed record C2(int I1, int I2) : C1(I1); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2 { I1 = 42, I2 = 43 }", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_RecordWithIndexer() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { private int field = 44; public int this[int i] => 0; public int PropertyWithoutGetter { set { } } public int P2 { get => 43; } public ref int P3 { get => ref field; } public event System.Action a; private int field1 = 100; internal int field2 = 100; protected int field3 = 100; private protected int field4 = 100; internal protected int field5 = 100; private int Property1 { get; set; } = 100; internal int Property2 { get; set; } = 100; protected int Property3 { get; set; } = 100; private protected int Property4 { get; set; } = 100; internal protected int Property5 { get; set; } = 100; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { I1 = 42, P2 = 43, P3 = 44 }", verify: Verification.Skipped /* init-only */); comp.VerifyEmitDiagnostics( // (12,32): warning CS0067: The event 'C1.a' is never used // public event System.Action a; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "a", isSuppressed: false).WithArguments("C1.a").WithLocation(12, 32), // (14,17): warning CS0414: The field 'C1.field1' is assigned but its value is never used // private int field1 = 100; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field1", isSuppressed: false).WithArguments("C1.field1").WithLocation(14, 17) ); } [Fact, WorkItem(47672, "https://github.com/dotnet/roslyn/issues/47672")] public void ToString_PrivateGetter() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public int P1 { private get => 43; set => throw null; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "C1 { P1 = 43 }"); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenVirtualProperty_NoRepetition() { var src = @" System.Console.WriteLine(new B() { P = 2 }.ToString()); abstract record A { public virtual int P { get; set; } } record B : A { public override int P { get; set; } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B { P = 2 }"); } [Fact, WorkItem(47797, "https://github.com/dotnet/roslyn/issues/47797")] public void ToString_OverriddenAbstractProperty_NoRepetition() { var src = @" System.Console.Write(new B1() { P = 1 }); System.Console.Write("" ""); System.Console.Write(new B2(2)); abstract record A1 { public abstract int P { get; set; } } record B1 : A1 { public override int P { get; set; } } abstract record A2(int P); record B2(int P) : A2(P); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "B1 { P = 1 } B2 { P = 2 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_ErrorBase() { var src = @" record C2: Error; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C2.ToString()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.EqualityContract': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C2.Equals(object?)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C2.GetHashCode()': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // record C2: Error; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record C2: Error; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 12) ); } [Fact, WorkItem(49263, "https://github.com/dotnet/roslyn/issues/49263")] public void ToString_SelfReferentialBase() { var src = @" record R : R; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0146: Circular base type dependency involving 'R' and 'R' // record R : R; Diagnostic(ErrorCode.ERR_CircularBase, "R").WithArguments("R", "R").WithLocation(2, 8), // (2,8): error CS0115: 'R.ToString()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R.EqualityContract': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R.Equals(object?)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R.GetHashCode()': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R.PrintMembers(StringBuilder)': no suitable method found to override // record R : R; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R").WithArguments("R.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8) ); } [Fact] public void ToString_TopLevelRecord_Empty_AbstractSealed() { var src = @" abstract sealed record C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,24): error CS0418: 'C1': an abstract type cannot be sealed or static // abstract sealed record C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C1").WithArguments("C1").WithLocation(2, 24) ); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Private, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ValueType() { var src = @" var c1 = new C1() { field = 42 }; System.Console.Write(c1.ToString()); record C1 { public int field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.False(print.IsOverride); Assert.True(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""int C1.field"" IL_0018: constrained. ""int"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ConstrainedValueType() { var src = @" var c1 = new C1<int>() { field = 42 }; System.Console.Write(c1.ToString()); record C1<T> where T : struct { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = 42 }"); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""T C1<T>.field"" IL_0018: constrained. ""T"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_ReferenceType() { var src = @" var c1 = new C1() { field = ""hello"" }; System.Console.Write(c1.ToString()); record C1 { public string field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 32 (0x20) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldc.i4.1 IL_001f: ret } "); } [Fact, WorkItem(47092, "https://github.com/dotnet/roslyn/issues/47092")] public void ToString_TopLevelRecord_OneField_Unconstrained() { var src = @" var c1 = new C1<string>() { field = ""hello"" }; System.Console.Write(c1.ToString()); System.Console.Write("" ""); var c2 = new C1<int>() { field = 42 }; System.Console.Write(c2.ToString()); record C1<T> { public T field; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { field = hello } C1 { field = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1<T>." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 37 (0x25) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""T C1<T>.field"" IL_0018: box ""T"" IL_001d: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0022: pop IL_0023: ldc.i4.1 IL_0024: ret } "); } [Fact] public void ToString_TopLevelRecord_OneField_ErrorType() { var src = @" record C1 { public Error field; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,12): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // public Error field; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 12), // (4,18): warning CS0649: Field 'C1.field' is never assigned to, and will always have its default value null // public Error field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C1.field", "null").WithLocation(4, 18) ); } [Fact] public void ToString_TopLevelRecord_TwoFields_ReferenceType() { var src = @" var c1 = new C1() { field1 = ""hi"", field2 = null }; System.Console.Write(c1.ToString()); record C1 { public string field1; public string field2; private string field3; internal string field4; protected string field5; protected internal string field6; private protected string field7; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (10,20): warning CS0169: The field 'C1.field3' is never used // private string field3; Diagnostic(ErrorCode.WRN_UnreferencedField, "field3").WithArguments("C1.field3").WithLocation(10, 20), // (11,21): warning CS0649: Field 'C1.field4' is never assigned to, and will always have its default value null // internal string field4; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field4").WithArguments("C1.field4", "null").WithLocation(11, 21), // (12,22): warning CS0649: Field 'C1.field5' is never assigned to, and will always have its default value null // protected string field5; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field5").WithArguments("C1.field5", "null").WithLocation(12, 22), // (13,31): warning CS0649: Field 'C1.field6' is never assigned to, and will always have its default value null // protected internal string field6; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field6").WithArguments("C1.field6", "null").WithLocation(13, 31), // (14,30): warning CS0649: Field 'C1.field7' is never assigned to, and will always have its default value null // private protected string field7; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field7").WithArguments("C1.field7", "null").WithLocation(14, 30) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { field1 = hi, field2 = }"); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 57 (0x39) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""field1 = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldfld ""string C1.field1"" IL_0018: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_001d: pop IL_001e: ldarg.1 IL_001f: ldstr "", field2 = "" IL_0024: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0029: pop IL_002a: ldarg.1 IL_002b: ldarg.0 IL_002c: ldfld ""string C1.field2"" IL_0031: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(object)"" IL_0036: pop IL_0037: ldc.i4.1 IL_0038: ret } "); } [Fact] public void ToString_TopLevelRecord_OneProperty() { var src = @" var c1 = new C1(Property: 42); System.Console.Write(c1.ToString()); record C1(int Property) { private int Property2; internal int Property3; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (7,17): warning CS0169: The field 'C1.Property2' is never used // private int Property2; Diagnostic(ErrorCode.WRN_UnreferencedField, "Property2").WithArguments("C1.Property2").WithLocation(7, 17), // (8,18): warning CS0649: Field 'C1.Property3' is never assigned to, and will always have its default value 0 // internal int Property3; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Property3").WithArguments("C1.Property3", "0").WithLocation(8, 18) ); var v = CompileAndVerify(comp, expectedOutput: "C1 { Property = 42 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 46 (0x2e) .maxstack 2 .locals init (int V_0) IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""Property = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: call ""int C1.Property.get"" IL_0018: stloc.0 IL_0019: ldloca.s V_0 IL_001b: constrained. ""int"" IL_0021: callvirt ""string object.ToString()"" IL_0026: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_002b: pop IL_002c: ldc.i4.1 IL_002d: ret }"); } [Fact] public void ToString_TopLevelRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1<int, string>(42, null) { field1 = 43, field2 = ""hi"" }; System.Console.Write(c1.ToString()); record C1<T1, T2>(T1 Property1, T2 Property2) { public T1 field1; public T2 field2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { Property1 = 42, Property2 = , field1 = 43, field2 = hi }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties() { var src = @" var c1 = new C1(42, 43) { A2 = 100, B2 = 101 }; System.Console.Write(c1.ToString()); record Base(int A1) { public int A2; } record C1(int A1, int B1) : Base(A1) { public int B2; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); var v = CompileAndVerify(comp, expectedOutput: "C1 { A1 = 42, A2 = 100, B1 = 43, B2 = 101 }", verify: Verification.Skipped /* init-only */); v.VerifyIL("C1." + WellKnownMemberNames.PrintMembersMethodName, @" { // Code size 98 (0x62) .maxstack 2 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool Base.PrintMembers(System.Text.StringBuilder)"" IL_0007: brfalse.s IL_0015 IL_0009: ldarg.1 IL_000a: ldstr "", "" IL_000f: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0014: pop IL_0015: ldarg.1 IL_0016: ldstr ""B1 = "" IL_001b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0020: pop IL_0021: ldarg.1 IL_0022: ldarg.0 IL_0023: call ""int C1.B1.get"" IL_0028: stloc.0 IL_0029: ldloca.s V_0 IL_002b: constrained. ""int"" IL_0031: callvirt ""string object.ToString()"" IL_0036: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_003b: pop IL_003c: ldarg.1 IL_003d: ldstr "", B2 = "" IL_0042: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0047: pop IL_0048: ldarg.1 IL_0049: ldarg.0 IL_004a: ldflda ""int C1.B2"" IL_004f: constrained. ""int"" IL_0055: callvirt ""string object.ToString()"" IL_005a: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_005f: pop IL_0060: ldc.i4.1 IL_0061: ret } "); } [Fact] public void ToString_DerivedRecord_AbstractSealed() { var src = @" record C1; abstract sealed record C2 : C1; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,24): error CS0418: 'C2': an abstract type cannot be sealed or static // abstract sealed record C2 : C1; Diagnostic(ErrorCode.ERR_AbstractSealedStatic, "C2").WithArguments("C2").WithLocation(3, 24) ); var print = comp.GetMember<MethodSymbol>("C2." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal(Accessibility.Protected, print.DeclaredAccessibility); Assert.True(print.IsOverride); Assert.False(print.IsVirtual); Assert.False(print.IsAbstract); Assert.False(print.IsSealed); Assert.True(print.IsImplicitlyDeclared); var toString = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.ObjectToString); Assert.Equal(Accessibility.Public, toString.DeclaredAccessibility); Assert.True(toString.IsOverride); Assert.False(toString.IsVirtual); Assert.False(toString.IsAbstract); Assert.False(toString.IsSealed); Assert.True(toString.IsImplicitlyDeclared); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_DerivedRecord_BaseHasSealedToString(bool usePreview) { var src = @" var c = new C2(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9, options: TestOptions.DebugExe); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } else { comp.VerifyEmitDiagnostics( // (7,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => "C1"; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(7, 35) ); } } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1; record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseTriesToOverride() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public override string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics( // (11,28): error CS0239: 'C2.ToString()': cannot override inherited member 'C1.ToString()' because it is sealed // public override string ToString() => "C2"; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "ToString").WithArguments("C2.ToString()", "C1.ToString()").WithLocation(11, 28) ); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringPrivate() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { private new string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseShadowsToStringNonSealed() { var src = @" C3 c3 = new C3(); System.Console.Write(c3.ToString()); C1 c1 = c3; System.Console.Write(c1.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new virtual string ToString() => ""C2""; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C2C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentSignature() { var src = @" var c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public string ToString(int n) => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_BaseBaseHasSealedToString_And_BaseHasToStringWithDifferentReturnType() { var src = @" C1 c = new C3(); System.Console.Write(c.ToString()); record C1 { public sealed override string ToString() => ""C1""; } record C2 : C1 { public new int ToString() => throw null; } record C3 : C2; "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1"); var actualMembers = comp.GetMember<NamedTypeSymbol>("C3").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C3.EqualityContract.get", "System.Type C3.EqualityContract { get; }", "System.Boolean C3." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C3.op_Inequality(C3? left, C3? right)", "System.Boolean C3.op_Equality(C3? left, C3? right)", "System.Int32 C3.GetHashCode()", "System.Boolean C3.Equals(System.Object? obj)", "System.Boolean C3.Equals(C2? other)", "System.Boolean C3.Equals(C3? other)", "C1 C3." + WellKnownMemberNames.CloneMethodName + "()", "C3..ctor(C3 original)", "C3..ctor()" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_ReverseOrder() { var src = @" var c1 = new C1(42, 43) { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); record Base(int A2) { public int A1; } record C1(int A2, int B2) : Base(A2) { public int B1; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A2 = 42, A1 = 100, B2 = 43, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int A1; } "; var src2 = @" partial record C1 { public int B1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { A1 = 100, B1 = 101 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_DerivedRecord_TwoFieldsAndTwoProperties_Partial_ReverseOrder() { var src1 = @" var c1 = new C1() { A1 = 100, B1 = 101 }; System.Console.Write(c1.ToString()); partial record C1 { public int B1; } "; var src2 = @" partial record C1 { public int A1; } "; var comp = CreateCompilation(new[] { src1, src2, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { B1 = 101, A1 = 100 }", verify: Verification.Skipped /* init-only */); } [Fact] public void ToString_BadBase_MissingToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""RAN"" IL_0005: ret } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void A::.ctor() IL_0006: ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } // no override for ToString } "; var source = @" var c = new C(); System.Console.Write(c); public record C : B { public override string ToString() => base.ToString(); } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] public void ToString_BadBase_PrintMembersSealed() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method final family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.PrintMembers(StringBuilder)': cannot override inherited member 'A.PrintMembers(StringBuilder)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersInaccessible() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method private hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.PrintMembers(StringBuilder)': return type must be 'int' to match overridden member 'A.PrintMembers(StringBuilder)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)", "A.PrintMembers(System.Text.StringBuilder)", "int").WithLocation(2, 15) ); } [Fact] public void EqualityContract_BadBase_ReturnsInt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance int32 get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance int32 EqualityContract() { .get instance int32 A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersIsAmbiguous() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance int32 '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_MissingPrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_DuplicatePrintMembers() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_BadBase_PrintMembersNotOverriddenInBase() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit B extends A { .method family hidebysig specialname virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality ( class B r1, class B r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance bool Equals ( class A other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals ( class B other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class B original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } // no override for PrintMembers } "; var source = @" public record C : B { protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,29): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(4, 29) ); var source2 = @" public record C : B; "; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public record C : B; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(2, 15) ); } [Fact] public void ToString_BadBase_PrintMembersWithModOpt() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder modopt(int64) builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); var print = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean B.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.ToTestDisplayString()); Assert.Equal("System.Boolean A.PrintMembers(System.Text.StringBuilder modopt(System.Int64) builder)", print.OverriddenMethod.ToTestDisplayString()); } [Fact] public void ToString_BadBase_NewToString() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.ToString()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.ToString()").WithLocation(2, 15) ); } [Fact] public void ToString_NewToString_SealedBaseToString() { var source = @" B b = new B(); System.Console.Write(b.ToString()); A a = b; System.Console.Write(a.ToString()); public record A { public sealed override string ToString() => ""A""; } public record B : A { public new string ToString() => ""B""; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "BA"); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_BadBase_SealedToString(bool usePreview) { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public final hidebysig virtual instance string ToString () cil managed { IL_0000: ldstr ""A"" IL_0001: ret } } "; var source = @" var b = new B(); System.Console.Write(b.ToString()); public record B : A { }"; var comp = CreateCompilationWithIL( new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "A"); } else { comp.VerifyEmitDiagnostics( // (5,15): error CS8912: Inheriting from a record with a sealed 'Object.ToString' is not supported in C# 9.0. Please use language version '10.0' or greater. // public record B : A { Diagnostic(ErrorCode.ERR_InheritingFromRecordWithSealedToString, "B").WithArguments("9.0", "10.0").WithLocation(5, 15) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { public override string ToString() => ""RAN""; } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); var print = comp.GetMember<MethodSymbol>("C1." + WellKnownMemberNames.PrintMembersMethodName); Assert.Equal("System.Boolean C1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", print.ToTestDisplayString()); } [Theory] [InlineData(false)] [InlineData(true)] public void ToString_TopLevelRecord_UserDefinedToString_Sealed(bool usePreview) { var src = @" record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyEmitDiagnostics(); } else { comp.VerifyEmitDiagnostics( // (4,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => throw null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(4, 35) ); } } [Fact] public void ToString_TopLevelRecord_UserDefinedToString_Sealed_InSealedRecord() { var src = @" sealed record C1 { public sealed override string ToString() => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_WithNullableStringBuilder() { var src = @" #nullable enable record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder? builder) => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_ErrorReturnType() { var src = @" record C1 { protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Error PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(4, 23) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongReturnType() { var src = @" record C1 { protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'C1.PrintMembers(StringBuilder)' must return 'bool'. // protected virtual int PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "bool").WithLocation(4, 27) ); } [Fact] public void ToString_UserDefinedPrintMembers_Sealed() { var src = @" record C1(int I1); record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8872: 'C2.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 36) ); } [Fact] public void ToString_UserDefinedPrintMembers_NonVirtual() { var src = @" record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_SealedInSealedRecord() { var src = @" record C1(int I1); sealed record C2(int I1, int I2) : C1(I1) { protected sealed override bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] public void ToString_UserDefinedPrintMembers_Static() { var src = @" sealed record C { private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8877: Record member 'C.PrintMembers(StringBuilder)' may not be static. // private static bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "PrintMembers").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers() { var src = @" var c1 = new C1(); System.Console.Write(c1.ToString()); record C1 { protected virtual bool PrintMembers(System.Text.StringBuilder builder) { builder.Append(""RAN""); return true; } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "C1 { RAN }"); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility() { var src = @" record C1 { public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,25): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 25) ); } [Fact] public void ToString_UserDefinedPrintMembers_WrongAccessibility_SealedRecord() { var src = @" sealed record C1 { protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,20): warning CS0628: 'C1.PrintMembers(StringBuilder)': new protected member declared in sealed type // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20), // (4,20): error CS8879: Record member 'C1.PrintMembers(StringBuilder)' must be private. // protected bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(4, 20) ); } [Fact] public void ToString_UserDefinedPrintMembers_DerivedRecord_WrongAccessibility() { var src = @" record B; record C1 : B { public bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,17): error CS8875: Record member 'C1.PrintMembers(StringBuilder)' must be protected. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 17), // (5,17): error CS8872: 'C1.PrintMembers(StringBuilder)' must allow overriding because the containing record is not sealed. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17), // (5,17): warning CS0114: 'C1.PrintMembers(StringBuilder)' hides inherited member 'B.PrintMembers(StringBuilder)'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // public bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 17) ); } [Fact] public void ToString_UserDefinedPrintMembers_New() { var src = @" record B; record C1 : B { protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,32): error CS8860: 'C1.PrintMembers(StringBuilder)' does not override expected method from 'B'. // protected new virtual bool PrintMembers(System.Text.StringBuilder builder) => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "PrintMembers").WithArguments("C1.PrintMembers(System.Text.StringBuilder)", "B").WithLocation(5, 32) ); } [Fact] public void ToString_TopLevelRecord_EscapedNamed() { var src = @" var c1 = new @base(); System.Console.Write(c1.ToString()); record @base; "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "base { }"); } [Fact] public void ToString_DerivedDerivedRecord() { var src = @" var r1 = new R1(1); System.Console.Write(r1.ToString()); System.Console.Write("" ""); var r2 = new R2(10, 11); System.Console.Write(r2.ToString()); System.Console.Write("" ""); var r3 = new R3(20, 21, 22); System.Console.Write(r3.ToString()); record R1(int I1); record R2(int I1, int I2) : R1(I1); record R3(int I1, int I2, int I3) : R2(I1, I2); "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "R1 { I1 = 1 } R2 { I1 = 10, I2 = 11 } R3 { I1 = 20, I2 = 21, I3 = 22 }", verify: Verification.Skipped /* init-only */); } [Fact] public void WithExpr24() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); var clone = verifier.Compilation.GetMember("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal("<Clone>$", clone.Name); } [Fact] public void WithExpr25() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr26() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } protected C(C other) { X = other.X; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr27() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(ref C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr28() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(in C other) : this(-1) { } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void WithExpr29() { string source = @" record C(int X) { public static void Main() { var c1 = new C(1); c1 = c1 with { }; var c2 = c1 with { X = 11 }; System.Console.WriteLine(c1.X); System.Console.WriteLine(c2.X); } protected C(out C other) : this(-1) { other = null; } } "; var verifier = CompileAndVerify(source, expectedOutput: @"1 11").VerifyDiagnostics(); verifier.VerifyIL("C." + WellKnownMemberNames.CloneMethodName, @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""C..ctor(C)"" IL_0006: ret } "); } [Fact] public void AccessibilityOfBaseCtor_01() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y); "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] public void AccessibilityOfBaseCtor_02() { var src = @" using System; record Base { protected Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} public static void Main() { var c = new C(1, 2); } } record C(int X, int Y) : Base(X, Y) {} "; CompileAndVerify(src, expectedOutput: @" 1 2 ").VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_03() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_04() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B(object P) : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_05() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A; "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(44898, "https://github.com/dotnet/roslyn/issues/44898")] public void AccessibilityOfBaseCtor_06() { var src = @" abstract record A { protected A() {} protected A(A x) {} }; record B : A {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExprNestedErrors() { var src = @" class C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = """"-3 }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(8, 13), // (8,26): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'int' // c = c with { X = ""-3 }; Diagnostic(ErrorCode.ERR_BadBinaryOps, @"""""-3").WithArguments("-", "string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprNoExpressionToPropertyTypeConversion() { var src = @" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = """" }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact] public void WithExprPropertyInaccessibleSet() { var src = @" record C { public int X { get; private set; } } class D { public static void Main() { var c = new C(); c = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,22): error CS0272: The property or indexer 'C.X' cannot be used in this context because the set accessor is inaccessible // c = c with { X = 0 }; Diagnostic(ErrorCode.ERR_InaccessibleSetter, "X").WithArguments("C.X").WithLocation(11, 22) ); } [Fact] public void WithExprSideEffects1() { var src = @" using System; record C(int X, int Y, int Z) { public static void Main() { var c = new C(0, 1, 2); c = c with { Y = W(""Y""), X = W(""X"") }; } public static int W(string s) { Console.WriteLine(s); return 0; } } "; var verifier = CompileAndVerify(src, expectedOutput: @" Y X").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 47 (0x2f) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: ldc.i4.2 IL_0003: newobj ""C..ctor(int, int, int)"" IL_0008: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000d: dup IL_000e: ldstr ""Y"" IL_0013: call ""int C.W(string)"" IL_0018: callvirt ""void C.Y.init"" IL_001d: dup IL_001e: ldstr ""X"" IL_0023: call ""int C.W(string)"" IL_0028: callvirt ""void C.X.init"" IL_002d: pop IL_002e: ret }"); var comp = (CSharpCompilation)verifier.Compilation; var tree = comp.SyntaxTrees.First(); var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { Y ... = W(""X"") }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ Y = W(""Y"" ... = W(""X"") }') Initializers(2): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'Y') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().First(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, 1, 2)') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, 1, 2)') Arguments(3): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '1') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Z) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (5) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'Y = W(""Y"")') Left: IPropertyReferenceOperation: System.Int32 C.Y { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'Y') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""Y"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""Y""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""Y"") (Syntax: '""Y""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = W(""X"")') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Right: IInvocationOperation (System.Int32 C.W(System.String s)) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'W(""X"")') Instance Receiver: null Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: s) (OperationKind.Argument, Type: null) (Syntax: '""X""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""X"") (Syntax: '""X""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with ... = W(""X"") };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with ... = W(""X"") }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { Y ... = W(""X"") }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void WithExprConversions1() { var src = @" using System; record C(long X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = 11 }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: "11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 32 (0x20) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_000c: dup IL_000d: ldc.i4.s 11 IL_000f: conv.i8 IL_0010: callvirt ""void C.X.init"" IL_0015: callvirt ""long C.X.get"" IL_001a: call ""void System.Console.WriteLine(long)"" IL_001f: ret }"); } [Fact] public void WithExprConversions2() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator long(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 44 (0x2c) .maxstack 3 .locals init (S V_0) //s IL_0000: ldc.i4.0 IL_0001: conv.i8 IL_0002: newobj ""C..ctor(long)"" IL_0007: ldloca.s V_0 IL_0009: ldc.i4.s 11 IL_000b: call ""S..ctor(int)"" IL_0010: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0015: dup IL_0016: ldloc.0 IL_0017: call ""long S.op_Implicit(S)"" IL_001c: callvirt ""void C.X.init"" IL_0021: callvirt ""long C.X.get"" IL_0026: call ""void System.Console.WriteLine(long)"" IL_002b: ret }"); } [Fact] public void WithExprConversions3() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = (int)s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion 11").VerifyDiagnostics(); } [Fact] public void WithExprConversions4() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static explicit operator long(S s) => s._i; } record C(long X) { public static void Main() { var c = new C(0); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (19,41): error CS0266: Cannot implicitly convert type 'S' to 'long'. An explicit conversion exists (are you missing a cast?) // Console.WriteLine((c with { X = s }).X); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "s").WithArguments("S", "long").WithLocation(19, 41) ); } [Fact] public void WithExprConversions5() { var src = @" using System; record C(object X) { public static void Main() { var c = new C(0); Console.WriteLine((c with { X = ""abc"" }).X); } }"; CompileAndVerify(src, expectedOutput: "abc").VerifyDiagnostics(); } [Fact] public void WithExprConversions6() { var src = @" using System; struct S { private int _i; public S(int i) { _i = i; } public static implicit operator int(S s) { Console.WriteLine(""conversion""); return s._i; } } record C { private readonly long _x; public long X { get => _x; init { Console.WriteLine(""set""); _x = value; } } public static void Main() { var c = new C(); var s = new S(11); Console.WriteLine((c with { X = s }).X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" conversion set 11").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 43 (0x2b) .maxstack 3 .locals init (S V_0) //s IL_0000: newobj ""C..ctor()"" IL_0005: ldloca.s V_0 IL_0007: ldc.i4.s 11 IL_0009: call ""S..ctor(int)"" IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldloc.0 IL_0015: call ""int S.op_Implicit(S)"" IL_001a: conv.i8 IL_001b: callvirt ""void C.X.init"" IL_0020: callvirt ""long C.X.get"" IL_0025: call ""void System.Console.WriteLine(long)"" IL_002a: ret }"); } [Fact] public void WithExprStaticProperty() { var src = @" record C { public static int X { get; set; } public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS0176: Member 'C.X' cannot be accessed with an instance reference; qualify it with a type name instead // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_ObjectProhibited, "X").WithArguments("C.X").WithLocation(9, 22) ); } [Fact] public void WithExprMethodAsArgument() { var src = @" record C { public int X() => 0; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,22): error CS1913: Member 'X' cannot be initialized. It is not a field or property. // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "X").WithArguments("X").WithLocation(9, 22) ); } [Fact] public void WithExprStaticWithMethod() { var src = @" class C { public int X = 0; public static C Clone() => null; public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(9, 13), // (10,13): error CS8808: The receiver type 'C' does not have an accessible parameterless instance method named "Clone". // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_CannotClone, "c").WithArguments("C").WithLocation(10, 13) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprStaticWithMethod2() { var src = @" class B { public B Clone() => null; } class C : B { public int X = 0; public static new C Clone() => null; // static public static void Main() { var c = new C(); c = c with { }; c = c with { X = 11 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0266: Cannot implicitly convert type 'B' to 'C'. An explicit conversion exists (are you missing a cast?) // c = c with { }; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "c with { }").WithArguments("B", "C").WithLocation(13, 13), // (14,22): error CS0117: 'B' does not contain a definition for 'X' // c = c with { X = 11 }; Diagnostic(ErrorCode.ERR_NoSuchMember, "X").WithArguments("B", "X").WithLocation(14, 22) ); } [Fact] public void WithExprBadMemberBadType() { var src = @" record C { public int X { get; init; } public static void Main() { var c = new C(); c = c with { X = ""a"" }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): error CS0029: Cannot implicitly convert type 'string' to 'int' // c = c with { X = "a" }; Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""a""").WithArguments("string", "int").WithLocation(8, 26) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExprCloneReturnDifferent() { var src = @" class B { public int X { get; init; } } class C : B { public B Clone() => new B(); public static void Main() { var c = new C(); var b = c with { X = 0 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithSemanticModel1() { var src = @" record C(int X, string Y) { public static void Main() { var c = new C(0, ""a""); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); var typeInfo = model.GetTypeInfo(withExpr); var c = comp.GlobalNamespace.GetTypeMember("C"); Assert.True(c.IsRecord); Assert.True(c.ISymbol.Equals(typeInfo.Type)); var x = c.GetMembers("X").Single(); var xId = withExpr.DescendantNodes().Single(id => id.ToString() == "X"); var symbolInfo = model.GetSymbolInfo(xId); Assert.True(x.ISymbol.Equals(symbolInfo.Symbol)); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C(0, ""a"")') Right: IObjectCreationOperation (Constructor: C..ctor(System.Int32 X, System.String Y)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C(0, ""a"")') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '0') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: '""a""') ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""a"") (Syntax: '""a""') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c with { X = 2 }') Value: IInvocationOperation (virtual C C." + WellKnownMemberNames.CloneMethodName + @"()) (OperationKind.Invocation, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Instance Receiver: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') Arguments(0) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; init; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c with { X = 2 }') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_01() { var src = @" class C { int X { get; set; } public static void Main() { var c = new C(); c = c with { X = 2 }; } }"; var comp = CreateCompilation(src); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var withExpr = root.DescendantNodes().OfType<WithExpressionSyntax>().Single(); comp.VerifyOperationTree(withExpr, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { X = 2 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') CloneMethod: null Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C) (Syntax: '{ X = 2 }') Initializers(1): ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'X') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')"); var main = root.DescendantNodes().OfType<MethodDeclarationSyntax>().Single(); Assert.Equal("Main", main.Identifier.ToString()); VerifyFlowGraph(comp, main, expectedFlowGraph: @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [C c] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'c = new C()') Left: ILocalReferenceOperation: c (IsDeclaration: True) (OperationKind.LocalReference, Type: C, IsImplicit) (Syntax: 'c = new C()') Right: IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()') Arguments(0) Initializer: null Next (Regular) Block[B2] Entering: {R2} .locals {R2} { CaptureIds: [0] [1] Block[B2] - Block Predecessors: [B1] Statements (4) IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c') Value: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c') Value: IInvalidOperation (OperationKind.Invalid, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Children(1): ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c') ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32) (Syntax: 'X = 2') Left: IPropertyReferenceOperation: System.Int32 C.X { get; set; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'X') Instance Receiver: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'c = c with { X = 2 };') Expression: ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsInvalid) (Syntax: 'c = c with { X = 2 }') Left: IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'c') Right: IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c') Next (Regular) Block[B3] Leaving: {R2} {R1} } } Block[B3] - Exit Predecessors: [B2] Statements (0) "); } [Fact] public void NoCloneMethod_02() { var source = @"#nullable enable class R { public object? P { get; set; } } class Program { static void Main() { R r = new R(); _ = r with { P = 2 }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,13): error CS8858: The receiver type 'R' is not a valid record type. // _ = r with { P = 2 }; Diagnostic(ErrorCode.ERR_CannotClone, "r").WithArguments("R").WithLocation(11, 13)); } [Fact] public void WithBadExprArg() { var src = @" record C(int X, int Y) { public static void Main() { var c = new C(0, 0); c = c with { 5 }; c = c with { { X = 2 } }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,22): error CS0747: Invalid initializer member declarator // c = c with { 5 }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "5").WithLocation(8, 22), // (9,22): error CS1513: } expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_RbraceExpected, "{").WithLocation(9, 22), // (9,22): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(9, 22), // (9,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.X' // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_ObjectRequired, "X").WithArguments("C.X").WithLocation(9, 24), // (9,30): error CS1002: ; expected // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(9, 30), // (9,33): error CS1597: Semicolon after method or accessor block is not valid // c = c with { { X = 2 } }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(9, 33), // (11,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(11, 1) ); var tree = comp.SyntaxTrees[0]; var root = tree.GetRoot(); var model = comp.GetSemanticModel(tree); VerifyClone(model); var withExpr1 = root.DescendantNodes().OfType<WithExpressionSyntax>().First(); comp.VerifyOperationTree(withExpr1, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { 5 }') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ 5 }') Initializers(1): IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '5') Children(1): ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5, IsInvalid) (Syntax: '5')"); var withExpr2 = root.DescendantNodes().OfType<WithExpressionSyntax>().Skip(1).Single(); comp.VerifyOperationTree(withExpr2, @" IWithOperation (OperationKind.With, Type: C, IsInvalid) (Syntax: 'c with { ') Operand: ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c') CloneMethod: C C." + WellKnownMemberNames.CloneMethodName + @"() Initializer: IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ ') Initializers(0)"); } [Fact] public void WithExpr_DefiniteAssignment_01() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = y = 42 }; y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_02() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { X = z = 42, Y = z.ToString() }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_03() { var src = @" record B(int X, string Y) { static void M(B b) { int z; _ = b with { Y = z.ToString(), X = z = 42 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,26): error CS0165: Use of unassigned local variable 'z' // _ = b with { Y = z.ToString(), X = z = 42 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(7, 26)); } [Fact] public void WithExpr_DefiniteAssignment_04() { var src = @" record B(int X) { static void M() { B b; _ = (b = new B(42)) with { X = b.X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_05() { var src = @" record B(int X) { static void M() { B b; _ = new B(b.X) with { X = (b = new B(42)).X }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,19): error CS0165: Use of unassigned local variable 'b' // _ = new B(b.X) with { X = new B(42).X }; Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(7, 19)); } [Fact] public void WithExpr_DefiniteAssignment_06() { var src = @" record B(int X) { static void M(B b) { int y; _ = b with { X = M(out y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_DefiniteAssignment_07() { var src = @" record B(int X) { static void M(B b) { _ = b with { X = M(out int y) }; y.ToString(); } static int M(out int y) { y = 42; return 43; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_01() { var src = @" #nullable enable record B(int X) { static void M(B b) { string? s = null; _ = b with { X = M(out s) }; s.ToString(); } static int M(out string s) { s = ""a""; return 42; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void WithExpr_NullableAnalysis_02() { var src = @" #nullable enable record B(string X) { static void M(B b, string? s) { b.X.ToString(); _ = b with { X = s }; // 1 b.X.ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,26): warning CS8601: Possible null reference assignment. // _ = b with { X = s }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(8, 26)); } [Fact] public void WithExpr_NullableAnalysis_03() { var src = @" #nullable enable record B(string? X) { static void M1(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 1 _ = b with { X = s }; if (flag) { b.X.ToString(); } // 2 } static void M2(B b, string s, bool flag) { if (flag) { b.X.ToString(); } // 3 b = b with { X = s }; if (flag) { b.X.ToString(); } } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(7, 21), // (9,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(9, 21), // (14,21): warning CS8602: Dereference of a possibly null reference. // if (flag) { b.X.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(14, 21)); } [Fact] public void WithExpr_NullableAnalysis_04() { var src = @" #nullable enable record B(int X) { static void M1(B? b) { var b1 = b with { X = 42 }; // 1 _ = b.ToString(); _ = b1.ToString(); } static void M2(B? b) { (b with { X = 42 }).ToString(); // 2 } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (7,18): warning CS8602: Dereference of a possibly null reference. // var b1 = b with { X = 42 }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 18), // (14,10): warning CS8602: Dereference of a possibly null reference. // (b with { X = 42 }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(14, 10)); } [Fact, WorkItem(44763, "https://github.com/dotnet/roslyn/issues/44763")] public void WithExpr_NullableAnalysis_05() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(bool flag) { B b = new B(""hello"", null); if (flag) { b.X.ToString(); // shouldn't warn b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); // shouldn't warn b.Y.ToString(); } }"; // records should propagate the nullability of the // constructor arguments to the corresponding properties. // https://github.com/dotnet/roslyn/issues/44763 var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(11, 13), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // shouldn't warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_06() { var src = @" #nullable enable record B { public string? X { get; init; } public string? Y { get; init; } static void M1(bool flag) { B b = new B { X = ""hello"", Y = null }; if (flag) { b.X.ToString(); b.Y.ToString(); // 1 } b = b with { Y = ""world"" }; b.X.ToString(); b.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // b.Y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Y").WithLocation(14, 13) ); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_07() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([AllowNull] string X) // 1 { static void M1(B b) { b.X.ToString(); b = b with { X = null }; // 2 b.X.ToString(); // 3 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,10): warning CS8601: Possible null reference assignment. // record B([AllowNull] string X) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "[AllowNull] string X").WithLocation(5, 10), // (10,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // b = b with { X = null }; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 26), // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact, WorkItem(44691, "https://github.com/dotnet/roslyn/issues/44691")] public void WithExpr_NullableAnalysis_08() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B([property: AllowNull][AllowNull] string X) { static void M1(B b) { b.X.ToString(); b = b with { X = null }; b.X.ToString(); // 1 b = new B((string?)null); b.X.ToString(); } }"; var comp = CreateCompilation(new[] { src, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.X").WithLocation(11, 9)); } [Fact] public void WithExpr_NullableAnalysis_09() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { B b2 = b1 with { X = ""hello"" }; B b3 = b1 with { Y = ""world"" }; B b4 = b2 with { Y = ""world"" }; b1.X.ToString(); // 1 b1.Y.ToString(); // 2 b2.X.ToString(); b2.Y.ToString(); // 3 b3.X.ToString(); // 4 b3.Y.ToString(); b4.X.ToString(); b4.Y.ToString(); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // b1.X.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.X").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // b1.Y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Y").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // b2.Y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Y").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // b3.X.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.X").WithLocation(15, 9)); } [Fact] public void WithExpr_NullableAnalysis_10() { var src = @" #nullable enable record B(string? X, string? Y) { static void M1(B b1) { string? local = ""hello""; _ = b1 with { X = local = null, Y = local.ToString() // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // Y = local.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local").WithLocation(11, 17)); } [Fact] public void WithExpr_NullableAnalysis_11() { var src = @" #nullable enable record B(string X, string Y) { static string M0(out string? s) { s = null; return ""hello""; } static void M1(B b1) { string? local = ""world""; _ = b1 with { X = M0(out local), Y = local // 1 }; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,17): warning CS8601: Possible null reference assignment. // Y = local // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "local").WithLocation(13, 17)); } [Fact] public void WithExpr_NullableAnalysis_VariantClone() { var src = @" #nullable enable record A { public string? Y { get; init; } public string? Z { get; init; } } record B(string? X) : A { public new string Z { get; init; } = ""zed""; static void M1(B b1) { b1.Z.ToString(); (b1 with { Y = ""hello"" }).Y.ToString(); (b1 with { Y = ""hello"" }).Z.ToString(); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(10, 21), // (11,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(11, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_MaybeNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: MaybeNull] public B Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; // 1 (b1 with { X = null }).ToString(); // 2 } } "; var comp = CreateCompilation(new[] { src, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,21): warning CS8602: Dereference of a possibly null reference. // _ = b1 with { X = null }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(13, 21), // (14,18): warning CS8602: Dereference of a possibly null reference. // (b1 with { X = null }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "{ X = null }").WithLocation(14, 18)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NotNullClone() { var src = @" #nullable enable using System.Diagnostics.CodeAnalysis; record B(string? X) { [return: NotNull] public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; _ = b1 with { X = null }; (b1 with { X = null }).ToString(); } } "; var comp = CreateCompilation(new[] { src, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/44859")] [WorkItem(44859, "https://github.com/dotnet/roslyn/issues/44859")] public void WithExpr_NullableAnalysis_NullableClone_NoInitializers() { var src = @" #nullable enable record B(string? X) { public B? Clone() => new B(X); static void M1(B b1) { _ = b1 with { }; (b1 with { }).ToString(); // 1 } } "; var comp = CreateCompilation(src); // Note: we expect to give a warning on `// 1`, but do not currently // due to limitations of object initializer analysis. // Tracking in https://github.com/dotnet/roslyn/issues/44759 comp.VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord() { var src = @" using System; record C { public int X { get; set; } public string Y { get; init; } public long Z; public event Action E; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; E = other.E; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3, E = () => { } }; var c2 = c with {}; Console.WriteLine(c.Equals(c2)); Console.WriteLine(ReferenceEquals(c, c2)); Console.WriteLine(c2.X); Console.WriteLine(c2.Y); Console.WriteLine(c2.Z); Console.WriteLine(ReferenceEquals(c.E, c2.E)); var c3 = c with { Y = ""3"", X = 2 }; Console.WriteLine(c.Y); Console.WriteLine(c3.Y); Console.WriteLine(c.X); Console.WriteLine(c3.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" True False 1 2 3 True 2 3 1 2").VerifyDiagnostics(); } [Fact] public void WithExprNominalRecord2() { var comp1 = CreateCompilation(@" public record C { public int X { get; set; } public string Y { get; init; } public long Z; public C() { } public C(C other) { X = other.X; Y = other.Y; Z = other.Z; } }"); var verifier = CompileAndVerify(@" class D { public C M(C c) => c with { X = 5, Y = ""a"", Z = 2, }; }", references: new[] { comp1.EmitToImageReference() }).VerifyDiagnostics(); verifier.VerifyIL("D.M", @" { // Code size 33 (0x21) .maxstack 3 IL_0000: ldarg.1 IL_0001: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0006: dup IL_0007: ldc.i4.5 IL_0008: callvirt ""void C.X.set"" IL_000d: dup IL_000e: ldstr ""a"" IL_0013: callvirt ""void C.Y.init"" IL_0018: dup IL_0019: ldc.i4.2 IL_001a: conv.i8 IL_001b: stfld ""long C.Z"" IL_0020: ret }"); } [Fact] public void WithExprAssignToRef1() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X => ref _a[0]; public static void Main() { var c = new C(0) { X = 5 }; Console.WriteLine(c.X); c = c with { X = 1 }; Console.WriteLine(c.X); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 5 1").VerifyDiagnostics(); verifier.VerifyIL("C.Main", @" { // Code size 51 (0x33) .maxstack 3 IL_0000: ldc.i4.0 IL_0001: newobj ""C..ctor(int)"" IL_0006: dup IL_0007: callvirt ""ref int C.X.get"" IL_000c: ldc.i4.5 IL_000d: stind.i4 IL_000e: dup IL_000f: callvirt ""ref int C.X.get"" IL_0014: ldind.i4 IL_0015: call ""void System.Console.WriteLine(int)"" IL_001a: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_001f: dup IL_0020: callvirt ""ref int C.X.get"" IL_0025: ldc.i4.1 IL_0026: stind.i4 IL_0027: callvirt ""ref int C.X.get"" IL_002c: ldind.i4 IL_002d: call ""void System.Console.WriteLine(int)"" IL_0032: ret }"); } [Fact] public void WithExprAssignToRef2() { var src = @" using System; record C(int Y) { private readonly int[] _a = new[] { 0 }; public ref int X { get => ref _a[0]; set { } } public static void Main() { var a = new[] { 0 }; var c = new C(0) { X = ref a[0] }; Console.WriteLine(c.X); c = c with { X = ref a[0] }; Console.WriteLine(c.X); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,9): error CS8147: Properties which return by reference cannot have set accessors // set { } Diagnostic(ErrorCode.ERR_RefPropertyCannotHaveSetAccessor, "set").WithArguments("C.X.set").WithLocation(9, 9), // (15,32): error CS1525: Invalid expression term 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref a[0]").WithArguments("ref").WithLocation(15, 32), // (15,32): error CS1073: Unexpected token 'ref' // var c = new C(0) { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(15, 32), // (17,26): error CS1073: Unexpected token 'ref' // c = c with { X = ref a[0] }; Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(17, 26) ); } [Fact] public void WithExpressionSameLHS() { var comp = CreateCompilation(@" record C(int X) { public static void Main() { var c = new C(0); c = c with { X = 1, X = 2}; } }"); comp.VerifyDiagnostics( // (7,29): error CS1912: Duplicate initialization of member 'X' // c = c with { X = 1, X = 2}; Diagnostic(ErrorCode.ERR_MemberAlreadyInitialized, "X").WithArguments("X").WithLocation(7, 29) ); } [Fact] public void WithExpr_ValEscape() { var text = @" using System; record R { public S1 Property { set { throw null; } } } class Program { static void Main() { var r = new R(); Span<int> local = stackalloc int[1]; _ = r with { Property = MayWrap(ref local) }; _ = new R() { Property = MayWrap(ref local) }; } static S1 MayWrap(ref Span<int> arg) { return default; } } ref struct S1 { public ref int this[int i] => throw null; } "; CreateCompilationWithMscorlibAndSpan(text).VerifyDiagnostics(); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_01() { var source = @"record A { internal A() { } public object P1 { get; set; } internal object P2 { get; set; } protected internal object P3 { get; set; } protected object P4 { get; set; } private protected object P5 { get; set; } private object P6 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P6 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_02() { var source = @"record A { internal A() { } private protected object P1 { get; set; } private object P2 { get; set; } private record B(object P1, object P2) : A { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,29): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 29), // (6,40): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // private record B(object P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 40) ); var actualMembers = GetProperties(comp, "A.B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type A.B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_03(bool useCompilationReference) { var sourceA = @"public record A { public A() { } internal object P { get; set; } } public record B(object Q) : A { public B() : this(null) { } } record C1(object P, object Q) : B { }"; var comp = CreateCompilation(sourceA); AssertEx.Equal(new[] { "System.Type C1.EqualityContract { get; }" }, GetProperties(comp, "C1").ToTestDisplayStrings()); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C2(object P, object Q) : B { }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,28): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C2(object P, object Q) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 28) ); AssertEx.Equal(new[] { "System.Type C2.EqualityContract { get; }", "System.Object C2.P { get; init; }" }, GetProperties(comp, "C2").ToTestDisplayStrings()); } [WorkItem(44616, "https://github.com/dotnet/roslyn/issues/44616")] [Fact] public void Inheritance_04() { var source = @"record A { internal A() { } public object P1 { get { return null; } set { } } public object P2 { get; init; } public object P3 { get; } public object P4 { set { } } public virtual object P5 { get; set; } public static object P6 { get; set; } public ref object P7 => throw null; } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(12, 17), // (12,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(12, 28), // (12,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(12, 39), // (12,50): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "object", "P4").WithLocation(12, 50), // (12,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(12, 50), // (12,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(12, 61), // (12,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(12, 72), // (12,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(12, 72), // (12,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(12, 83)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_05() { var source = @"record A { internal A() { } public object P1 { get; set; } public int P2 { get; set; } } record B(int P1, object P2) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "int", "P1").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(7, 14), // (7,25): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record B(int P1, object P2) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "object", "P2").WithLocation(7, 25), // (7,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(int P1, object P2) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(7, 25)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_06() { var source = @"record A { internal int X { get; set; } internal int Y { set { } } internal int Z; } record B(int X, int Y, int Z) : A { } class Program { static void Main() { var b = new B(1, 2, 3); b.X = 4; b.Y = 5; b.Z = 6; ((A)b).X = 7; ((A)b).Y = 8; ((A)b).Z = 9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): error CS8866: Record member 'A.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("A.Y", "int", "Y").WithLocation(7, 21), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (7,24): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int Z").WithArguments("positional fields in records", "10.0").WithLocation(7, 24), // (7,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y, int Z) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(7, 28)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_07() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } } abstract record B1(int X, int Y) : A { } record B2(int X, int Y) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,24): error CS0546: 'B1.X.init': cannot override because 'A.X' does not have an overridable set accessor // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B1.X.init", "A.X").WithLocation(6, 24), // (6,31): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record B1(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 31), // (9,15): error CS0546: 'B2.X.init': cannot override because 'A.X' does not have an overridable set accessor // record B2(int X, int Y) : A Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("B2.X.init", "A.X").WithLocation(9, 15), // (9,22): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B2(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 22)); AssertEx.Equal(new[] { "System.Type B1.EqualityContract { get; }", "System.Int32 B1.X { get; init; }" }, GetProperties(comp, "B1").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type B2.EqualityContract { get; }", "System.Int32 B2.X { get; init; }" }, GetProperties(comp, "B2").ToTestDisplayStrings()); var b1Ctor = comp.GetTypeByMetadataName("B1")!.GetMembersUnordered().OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("B1..ctor(System.Int32 X, System.Int32 Y)", b1Ctor.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, b1Ctor.DeclaredAccessibility); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_08() { var source = @"abstract record A { public abstract int X { get; } public virtual int Y { get; } public virtual int Z { get; } } abstract record B : A { public override abstract int Y { get; } } record C(int X, int Y, int Z) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): error CS0546: 'C.X.init': cannot override because 'A.X' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "X").WithArguments("C.X.init", "A.X").WithLocation(11, 14), // (11,21): error CS0546: 'C.Y.init': cannot override because 'B.Y' does not have an overridable set accessor // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.ERR_NoSetToOverride, "Y").WithArguments("C.Y.init", "B.Y").WithLocation(11, 21), // (11,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; init; }", "System.Int32 C.Y { get; init; }" }, actualMembers); } [Fact, WorkItem(48947, "https://github.com/dotnet/roslyn/issues/48947")] public void Inheritance_09() { var source = @"abstract record C(int X, int Y) { public abstract int X { get; } public virtual int Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,23): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(1, 23), // (1,30): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(1, 30) ); NamedTypeSymbol c = comp.GetMember<NamedTypeSymbol>("C"); var actualMembers = c.GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Int32 C.X { get; }", "System.Int32 C.X.get", "System.Int32 C.<Y>k__BackingField", "System.Int32 C.Y { get; }", "System.Int32 C.Y.get", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); var expectedMemberNames = new[] { ".ctor", "get_EqualityContract", "EqualityContract", "X", "get_X", "<Y>k__BackingField", "Y", "get_Y", "ToString", "PrintMembers", "op_Inequality", "op_Equality", "GetHashCode", "Equals", "Equals", "<Clone>$", ".ctor", "Deconstruct" }; AssertEx.Equal(expectedMemberNames, c.GetPublicSymbol().MemberNames); var expectedCtors = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", }; AssertEx.Equal(expectedCtors, c.GetPublicSymbol().Constructors.ToTestDisplayStrings()); } [Fact] public void Inheritance_10() { var source = @"using System; interface IA { int X { get; } } interface IB { int Y { get; } } record C(int X, int Y) : IA, IB { } class Program { static void Main() { var c = new C(1, 2); Console.WriteLine(""{0}, {1}"", c.X, c.Y); Console.WriteLine(""{0}, {1}"", ((IA)c).X, ((IB)c).Y); } }"; CompileAndVerify(source, expectedOutput: @"1, 2 1, 2").VerifyDiagnostics(); } [Fact] public void Inheritance_11() { var source = @"interface IA { int X { get; } } interface IB { object Y { get; set; } } record C(object X, object Y) : IA, IB { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,32): error CS0738: 'C' does not implement interface member 'IA.X'. 'C.X' cannot implement 'IA.X' because it does not have the matching return type of 'int'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "IA").WithArguments("C", "IA.X", "C.X", "int").WithLocation(9, 32), // (9,36): error CS8854: 'C' does not implement interface member 'IB.Y.set'. 'C.Y.init' cannot implement 'IB.Y.set'. // record C(object X, object Y) : IA, IB Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongInitOnly, "IB").WithArguments("C", "IB.Y.set", "C.Y.init").WithLocation(9, 36) ); } [Fact] public void Inheritance_12() { var source = @"record A { public object X { get; } public object Y { get; } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(6, 17), // (6,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(6, 27), // (8,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(8, 19), // (9,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(9, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_13() { var source = @"record A(object X, object Y) { internal A() : this(null, null) { } } record B(object X, object Y) : A { public object X { get; } public object Y { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 17), // (5,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(object X, object Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 27), // (7,19): warning CS0108: 'B.X' hides inherited member 'A.X'. Use the new keyword if hiding was intended. // public object X { get; } Diagnostic(ErrorCode.WRN_NewRequired, "X").WithArguments("B.X", "A.X").WithLocation(7, 19), // (8,19): warning CS0108: 'B.Y' hides inherited member 'A.Y'. Use the new keyword if hiding was intended. // public object Y { get; } Diagnostic(ErrorCode.WRN_NewRequired, "Y").WithArguments("B.Y", "A.Y").WithLocation(8, 19)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.X { get; }", "System.Object B.Y { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_14() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B : A { public new int P1 { get; } public new int P2 { get; } } record C(object P1, int P2, object P3, int P4) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(13, 17), // (13,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(13, 17), // (13,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(13, 25), // (13,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(13, 36), // (13,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(13, 44), // (13,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, int P2, object P3, int P4) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(13, 44)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_15() { var source = @"record C(int P1, object P2) { public object P1 { get; set; } public int P2 { get; set; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,14): error CS8866: Record member 'C.P1' must be a readable instance property or field of type 'int' to match positional parameter 'P1'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("C.P1", "int", "P1").WithLocation(1, 14), // (1,14): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 14), // (1,25): error CS8866: Record member 'C.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(int P1, object P2) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("C.P2", "object", "P2").WithLocation(1, 25), // (1,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(int P1, object P2) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 25)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Int32 C.P2 { get; set; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_16() { var source = @"record A { public int P1 { get; } public int P2 { get; } public int P3 { get; } public int P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'int' to match positional parameter 'P2'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "int", "P2").WithLocation(8, 25), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(8, 36), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; }", "System.Object B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_17() { var source = @"record A { public object P1 { get; } public object P2 { get; } public object P3 { get; } public object P4 { get; } } record B(object P1, int P2, object P3, int P4) : A { public new int P1 { get; } public new int P2 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,17): error CS8866: Record member 'B.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("B.P1", "object", "P1").WithLocation(8, 17), // (8,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(8, 17), // (8,25): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(8, 25), // (8,36): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(8, 36), // (8,44): error CS8866: Record member 'A.P4' must be a readable instance property or field of type 'int' to match positional parameter 'P4'. // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("A.P4", "int", "P4").WithLocation(8, 44), // (8,44): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, int P2, object P3, int P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(8, 44)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Int32 B.P1 { get; }", "System.Int32 B.P2 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_18() { var source = @"record C(object P1, object P2, object P3, object P4, object P5) { public object P1 { get { return null; } set { } } public object P2 { get; } public object P3 { set { } } public static object P4 { get; set; } public ref object P5 => throw null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'C.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("C.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39), // (1,50): error CS8866: Record member 'C.P4' must be a readable instance property or field of type 'object' to match positional parameter 'P4'. // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P4").WithArguments("C.P4", "object", "P4").WithLocation(1, 50), // (1,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(1, 50), // (1,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2, object P3, object P4, object P5) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(1, 61)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; set; }", "System.Object C.P2 { get; }", "System.Object C.P3 { set; }", "System.Object C.P4 { get; set; }", "ref System.Object C.P5 { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_19() { var source = @"#pragma warning disable 8618 #nullable enable record A { internal A() { } public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } } record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(15, 18), // (15,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(15, 31), // (15,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(15, 42), // (15,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(15, 56), // (15,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(15, 71), // (15,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(15, 92), // (15,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(15, 110), // (15,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record B(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(15, 122) ); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_20() { var source = @"#pragma warning disable 8618 #nullable enable record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) { public object P1 { get; } public dynamic[] P2 { get; } public object? P3 { get; } public object[] P4 { get; } public (int X, int Y) P5 { get; } public (int, int)[] P6 { get; } public nint P7 { get; } public System.UIntPtr[] P8 { get; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,18): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(3, 18), // (3,31): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(3, 31), // (3,42): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(3, 42), // (3,56): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(3, 56), // (3,71): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(3, 71), // (3,92): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(3, 92), // (3,110): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(3, 110), // (3,122): warning CS8907: Parameter 'P8' is unread. Did you forget to use it to initialize the property with that name? // record C(dynamic P1, object[] P2, object P3, object?[] P4, (int, int) P5, (int X, int Y)[] P6, System.IntPtr P7, nuint[] P8) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P8").WithArguments("P8").WithLocation(3, 122) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P1 { get; }", "dynamic[] C.P2 { get; }", "System.Object? C.P3 { get; }", "System.Object[] C.P4 { get; }", "(System.Int32 X, System.Int32 Y) C.P5 { get; }", "(System.Int32, System.Int32)[] C.P6 { get; }", "nint C.P7 { get; }", "System.UIntPtr[] C.P8 { get; }" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Inheritance_21(bool useCompilationReference) { var sourceA = @"public record A { public object P1 { get; } internal object P2 { get; } } public record B : A { internal new object P1 { get; } public new object P2 { get; } }"; var comp = CreateCompilation(sourceA); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B { } class Program { static void Main() { var c = new C(1, 2); System.Console.WriteLine(""({0}, {1})"", c.P1, c.P2); } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); var verifier = CompileAndVerify(comp, expectedOutput: "(, )").VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28) ); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""B..ctor()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(C)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ret }"); verifier.VerifyIL("Program.Main", @"{ // Code size 41 (0x29) .maxstack 3 .locals init (C V_0) //c IL_0000: ldc.i4.1 IL_0001: box ""int"" IL_0006: ldc.i4.2 IL_0007: box ""int"" IL_000c: newobj ""C..ctor(object, object)"" IL_0011: stloc.0 IL_0012: ldstr ""({0}, {1})"" IL_0017: ldloc.0 IL_0018: callvirt ""object A.P1.get"" IL_001d: ldloc.0 IL_001e: callvirt ""object B.P2.get"" IL_0023: call ""void System.Console.WriteLine(string, object, object)"" IL_0028: ret }"); } [Fact] public void Inheritance_22() { var source = @"record A { public ref object P1 => throw null; public object P2 => throw null; } record B : A { public new object P1 => throw null; public new ref object P2 => throw null; } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28) ); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_23() { var source = @"record A { public static object P1 { get; } public object P2 { get; } } record B : A { public new object P1 { get; } public new static object P2 { get; } } record C(object P1, object P2) : B { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): error CS8866: Record member 'B.P2' must be a readable instance property or field of type 'object' to match positional parameter 'P2'. // record C(object P1, object P2) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("B.P2", "object", "P2").WithLocation(11, 28), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record C(object P1, object P2) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_24() { var source = @"record A { public object get_P() => null; public object set_Q() => null; } record B(object P, object Q) : A { } record C(object P) { public object get_P() => null; public object set_Q() => null; }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (9,17): error CS0082: Type 'C' already reserves a member called 'get_P' with the same parameter types // record C(object P) Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("get_P", "C").WithLocation(9, 17)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var expectedMembers = new[] { "B..ctor(System.Object P, System.Object Q)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Object B.<P>k__BackingField", "System.Object B.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.P.init", "System.Object B.P { get; init; }", "System.Object B.<Q>k__BackingField", "System.Object B.Q.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Q.init", "System.Object B.Q { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Object P, out System.Object Q)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings()); expectedMembers = new[] { "C..ctor(System.Object P)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.Object C.<P>k__BackingField", "System.Object C.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) C.P.init", "System.Object C.P { get; init; }", "System.Object C.get_P()", "System.Object C.set_Q()", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(C? other)", "C C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Object P)" }; AssertEx.Equal(expectedMembers, comp.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings()); } [Fact] public void Inheritance_25() { var sourceA = @"public record A { public class P1 { } internal object P2 = 2; public int P3(object o) => 3; internal int P4<T>(T t) => 4; }"; var sourceB = @"record B(object P1, object P2, object P3, object P4) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,21): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "object P2").WithArguments("positional fields in records", "10.0").WithLocation(1, 21), // (1,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(1, 28), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'object' to match positional parameter 'P1'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "object", "P1").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(1, 17), // (1,39): error CS8866: Record member 'A.P3' must be a readable instance property or field of type 'object' to match positional parameter 'P3'. // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P3").WithArguments("A.P3", "object", "P3").WithLocation(1, 39), // (1,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(1, 39)); actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P2 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_26() { var sourceA = @"public record A { internal const int P = 4; }"; var sourceB = @"record B(object P) : A { }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (1,17): error CS8866: Record member 'A.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record B(object P) : A Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("A.P", "object", "P").WithLocation(1, 17), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); comp = CreateCompilation(sourceA); var refA = comp.EmitToImageReference(); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Fact] public void Inheritance_27() { var source = @"record A { public object P { get; } public object Q { get; set; } } record B(object get_P, object set_Q) : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.get_P { get; init; }", "System.Object B.set_Q { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_28() { var source = @"interface I { object P { get; } } record A : I { object I.P => null; } record B(object P) : A { } record C(object P) : I { object I.P => null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P { get; init; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; init; }", "System.Object C.I.P { get; }" }, GetProperties(comp, "C").ToTestDisplayStrings()); } [Fact] public void Inheritance_29() { var sourceA = @"Public Class A Public Property P(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property Q(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { object P { get; } }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Q { get; init; }", "System.Object B.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_30() { var sourceA = @"Public Class A Public ReadOnly Overloads Property P() As Object Get Return Nothing End Get End Property Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record B(object P, object Q) : A { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'B.Equals(A?)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.Equals(A?)").WithLocation(1, 8), // (1,8): error CS0115: 'B.PrintMembers(StringBuilder)': no suitable method found to override // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS8867: No accessible copy constructor found in base type 'A'. // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "B").WithArguments("A").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object P, object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,32): error CS8864: Records may only inherit from object or another record // record B(object P, object Q) : A Diagnostic(ErrorCode.ERR_BadRecordBase, "A").WithLocation(1, 32) ); var actualMembers = GetProperties(compB, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void Inheritance_31() { var sourceA = @"Public Class A Public ReadOnly Property P() As Object Get Return Nothing End Get End Property Public Property Q(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Property R(o As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(a as A) End Sub End Class Public Class B Inherits A Public ReadOnly Overloads Property P(o As Object) As Object Get Return Nothing End Get End Property Public Overloads Property Q() As Object Get Return Nothing End Get Set End Set End Property Public Overloads Property R(x As Object, y As Object) As Object Get Return Nothing End Get Set End Set End Property Public Sub New(b as B) MyBase.New(b) End Sub End Class "; var compA = CreateVisualBasicCompilation(sourceA); compA.VerifyDiagnostics(); var refA = compA.EmitToImageReference(); var sourceB = @"record C(object P, object Q, object R) : B { }"; var compB = CreateCompilation(new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (1,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'C.Equals(B?)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(B?)").WithLocation(1, 8), // (1,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,8): error CS7036: There is no argument given that corresponds to the required formal parameter 'b' of 'B.B(B)' // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("b", "B.B(B)").WithLocation(1, 8), // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (1,42): error CS8864: Records may only inherit from object or another record // record C(object P, object Q, object R) : B Diagnostic(ErrorCode.ERR_BadRecordBase, "B").WithLocation(1, 42) ); var actualMembers = GetProperties(compB, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.R { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Inheritance_32() { var source = @"record A { public virtual object P1 { get; } public virtual object P2 { get; set; } public virtual object P3 { get; protected init; } public virtual object P4 { protected get; init; } public virtual object P5 { init { } } public virtual object P6 { set { } } public static object P7 { get; set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(11, 17), // (11,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(11, 28), // (11,39): warning CS8907: Parameter 'P3' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P3").WithArguments("P3").WithLocation(11, 39), // (11,50): warning CS8907: Parameter 'P4' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P4").WithArguments("P4").WithLocation(11, 50), // (11,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(11, 61), // (11,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(11, 61), // (11,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(11, 72), // (11,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(11, 72), // (11,83): error CS8866: Record member 'A.P7' must be a readable instance property or field of type 'object' to match positional parameter 'P7'. // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P7").WithArguments("A.P7", "object", "P7").WithLocation(11, 83), // (11,83): warning CS8907: Parameter 'P7' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6, object P7) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P7").WithArguments("P7").WithLocation(11, 83)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_33() { var source = @"abstract record A { public abstract object P1 { get; } public abstract object P2 { get; set; } public abstract object P3 { get; protected init; } public abstract object P4 { protected get; init; } public abstract object P5 { init; } public abstract object P6 { set; } } record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P6.set' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P6.set").WithLocation(10, 8), // (10,8): error CS0534: 'B' does not implement inherited abstract member 'A.P5.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P5.init").WithLocation(10, 8), // (10,17): error CS0546: 'B.P1.init': cannot override because 'A.P1' does not have an overridable set accessor // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_NoSetToOverride, "P1").WithArguments("B.P1.init", "A.P1").WithLocation(10, 17), // (10,28): error CS8853: 'B.P2' must match by init-only of overridden member 'A.P2' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeInitOnlyOnOverride, "P2").WithArguments("B.P2", "A.P2").WithLocation(10, 28), // (10,39): error CS0507: 'B.P3.init': cannot change access modifiers when overriding 'protected' inherited member 'A.P3.init' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P3").WithArguments("B.P3.init", "protected", "A.P3.init").WithLocation(10, 39), // (10,50): error CS0507: 'B.P4.get': cannot change access modifiers when overriding 'protected' inherited member 'A.P4.get' // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "P4").WithArguments("B.P4.get", "protected", "A.P4.get").WithLocation(10, 50), // (10,61): error CS8866: Record member 'A.P5' must be a readable instance property or field of type 'object' to match positional parameter 'P5'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P5").WithArguments("A.P5", "object", "P5").WithLocation(10, 61), // (10,61): warning CS8907: Parameter 'P5' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P5").WithArguments("P5").WithLocation(10, 61), // (10,72): error CS8866: Record member 'A.P6' must be a readable instance property or field of type 'object' to match positional parameter 'P6'. // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P6").WithArguments("A.P6", "object", "P6").WithLocation(10, 72), // (10,72): warning CS8907: Parameter 'P6' is unread. Did you forget to use it to initialize the property with that name? // record B(object P1, object P2, object P3, object P4, object P5, object P6) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P6").WithArguments("P6").WithLocation(10, 72)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.P1 { get; init; }", "System.Object B.P2 { get; init; }", "System.Object B.P3 { get; init; }", "System.Object B.P4 { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_34() { var source = @"abstract record A { public abstract object P1 { get; init; } public virtual object P2 { get; init; } } record B(string P1, string P2) : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.init' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.init").WithLocation(6, 8), // (6,8): error CS0534: 'B' does not implement inherited abstract member 'A.P1.get' // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P1.get").WithLocation(6, 8), // (6,17): error CS8866: Record member 'A.P1' must be a readable instance property or field of type 'string' to match positional parameter 'P1'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P1").WithArguments("A.P1", "string", "P1").WithLocation(6, 17), // (6,17): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(6, 17), // (6,28): error CS8866: Record member 'A.P2' must be a readable instance property or field of type 'string' to match positional parameter 'P2'. // record B(string P1, string P2) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P2").WithArguments("A.P2", "string", "P2").WithLocation(6, 28), // (6,28): warning CS8907: Parameter 'P2' is unread. Did you forget to use it to initialize the property with that name? // record B(string P1, string P2) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P2").WithArguments("P2").WithLocation(6, 28)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_35() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; } public abstract object Y { get; init; } } record B(object X, object Y) : A(X, Y) { public override object X { get; } = X; } class Program { static void Main() { B b = new B(1, 2); A a = b; WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Object B.Y { get; init; }", "System.Object B.X { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.2 IL_0002: stfld ""object B.<Y>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld ""object B.<X>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""A..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object B.<Y>k__BackingField"" IL_000e: stfld ""object B.<Y>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object B.<X>k__BackingField"" IL_001a: stfld ""object B.<X>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object B.<X>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object B.<X>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object B.<Y>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object B.<X>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_36() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } } abstract record B : A { public abstract object Y { get; init; } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine(a.X); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) 1 (1, 2)").VerifyDiagnostics(); verifier.VerifyIL("A..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); verifier.VerifyIL("B..ctor()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""A..ctor()"" IL_0006: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: call ""B..ctor()"" IL_0014: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object B.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_37() { var source = @"using static System.Console; abstract record A(object X, object Y) { public abstract object X { get; init; } public virtual object Y { get; init; } } abstract record B(object X, object Y) : A(X, Y) { public override abstract object X { get; init; } public override abstract object Y { get; init; } } record C(object X, object Y) : B(X, Y); class Program { static void Main() { C c = new C(1, 2); B b = c; A a = c; WriteLine((c.X, c.Y)); WriteLine((b.X, b.Y)); WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); (x, y) = b; WriteLine((x, y)); (x, y) = a; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.X { get; init; }", "System.Object C.Y { get; init; }", }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"(1, 2) (1, 2) (1, 2) (1, 2) (1, 2) (1, 2)").VerifyDiagnostics( // (2,26): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 26), // (2,36): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // abstract record A(object X, object Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(2, 36) ); verifier.VerifyIL("A..ctor(object, object)", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret }"); verifier.VerifyIL("A..ctor(A)", @"{ // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object A.<Y>k__BackingField"" IL_000d: stfld ""object A.<Y>k__BackingField"" IL_0012: ret }"); verifier.VerifyIL("A.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""object A.<Y>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""object A.<Y>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("A.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type A.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""object A.<Y>k__BackingField"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0026: add IL_0027: ret }"); verifier.VerifyIL("B..ctor(object, object)", @"{ // Code size 9 (0x9) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: call ""A..ctor(object, object)"" IL_0008: ret }"); verifier.VerifyIL("B..ctor(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""A..ctor(A)"" IL_0007: ret }"); verifier.VerifyIL("B.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); verifier.VerifyIL("C..ctor(object, object)", @"{ // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""object C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""object C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldarg.1 IL_0010: ldarg.2 IL_0011: call ""B..ctor(object, object)"" IL_0016: ret }"); verifier.VerifyIL("C..ctor(C)", @"{ // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<X>k__BackingField"" IL_000e: stfld ""object C.<X>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<Y>k__BackingField"" IL_001a: stfld ""object C.<Y>k__BackingField"" IL_001f: ret }"); verifier.VerifyIL("C.Deconstruct", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: callvirt ""object A.X.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: callvirt ""object A.Y.get"" IL_000f: stind.ref IL_0010: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 64 (0x40) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_003e IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_003c IL_000d: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""object C.<X>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""object C.<X>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_0023: brfalse.s IL_003c IL_0025: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_002a: ldarg.0 IL_002b: ldfld ""object C.<Y>k__BackingField"" IL_0030: ldarg.1 IL_0031: ldfld ""object C.<Y>k__BackingField"" IL_0036: callvirt ""bool System.Collections.Generic.EqualityComparer<object>.Equals(object, object)"" IL_003b: ret IL_003c: ldc.i4.0 IL_003d: ret IL_003e: ldc.i4.1 IL_003f: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""object C.<X>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_001c: add IL_001d: ldc.i4 0xa5555529 IL_0022: mul IL_0023: call ""System.Collections.Generic.EqualityComparer<object> System.Collections.Generic.EqualityComparer<object>.Default.get"" IL_0028: ldarg.0 IL_0029: ldfld ""object C.<Y>k__BackingField"" IL_002e: callvirt ""int System.Collections.Generic.EqualityComparer<object>.GetHashCode(object)"" IL_0033: add IL_0034: ret }"); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_38() { var source = @"using static System.Console; abstract record A { public abstract object X { get; init; } public abstract object Y { get; init; } } abstract record B : A { public new void X() { } public new struct Y { } } record C(object X, object Y) : B; class Program { static void Main() { C c = new C(1, 2); A a = c; WriteLine((a.X, a.Y)); var (x, y) = c; WriteLine((x, y)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (9,21): error CS0533: 'B.X()' hides inherited abstract member 'A.X' // public new void X() { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "X").WithArguments("B.X()", "A.X").WithLocation(9, 21), // (10,23): error CS0533: 'B.Y' hides inherited abstract member 'A.Y' // public new struct Y { } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "Y").WithArguments("B.Y", "A.Y").WithLocation(10, 23), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.get' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.get").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.X.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.X.init").WithLocation(12, 8), // (12,8): error CS0534: 'C' does not implement inherited abstract member 'A.Y.init' // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.Y.init").WithLocation(12, 8), // (12,17): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'object' to match positional parameter 'X'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "object", "X").WithLocation(12, 17), // (12,17): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 17), // (12,27): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'object' to match positional parameter 'Y'. // record C(object X, object Y) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "object", "Y").WithLocation(12, 27), // (12,27): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(object X, object Y) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 27)); AssertEx.Equal(new[] { "System.Type C.EqualityContract { get; }", }, GetProperties(comp, "C").ToTestDisplayStrings()); } // Member in intermediate base that hides abstract property. Not supported. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_39() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } .class public abstract B extends A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void A::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class B A_1) { ldnull throw } .method public hidebysig specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .method public hidebysig instance object P() { ldnull ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record CA(object P) : A; record CB(object P) : B; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.get' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.get").WithLocation(2, 8), // (2,8): error CS0534: 'CB' does not implement inherited abstract member 'A.P.init' // record CB(object P) : B; Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "CB").WithArguments("CB", "A.P.init").WithLocation(2, 8), // (2,18): error CS8866: Record member 'B.P' must be a readable instance property or field of type 'object' to match positional parameter 'P'. // record CB(object P) : B; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("B.P", "object", "P").WithLocation(2, 18), // (2,18): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record CB(object P) : B; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 18)); AssertEx.Equal(new[] { "System.Type CA.EqualityContract { get; }", "System.Object CA.P { get; init; }" }, GetProperties(comp, "CA").ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.Type CB.EqualityContract { get; }" }, GetProperties(comp, "CB").ToTestDisplayStrings()); } // Accessor names that do not match the property name. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_40() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::GetProperty1() } .property instance object P() { .get instance object A::GetProperty2() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::SetProperty2(object) } .method family virtual instance class [mscorlib]System.Type GetProperty1() { ldnull ret } .method public abstract virtual instance object GetProperty2() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) SetProperty2(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "GetProperty1", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "GetProperty2", "SetProperty2"); } // Accessor names that do not match the property name and are not valid C# names. [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_41() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::'EqualityContract<>get'() } .property instance object P() { .get instance object A::'P<>get'() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::'P<>set'(object) } .method family virtual instance class [mscorlib]System.Type 'EqualityContract<>get'() { ldnull ret } .method public abstract virtual instance object 'P<>get'() { } .method public abstract virtual instance void modreq(System.Runtime.CompilerServices.IsExternalInit) 'P<>set'(object 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); VerifyProperty(actualMembers[0], "System.Type B.EqualityContract { get; }", "EqualityContract<>get", null); VerifyProperty(actualMembers[1], "System.Object B.P { get; init; }", "P<>get", "P<>set"); } private static void VerifyProperty(Symbol symbol, string propertyDescription, string? getterName, string? setterName) { var property = (PropertySymbol)symbol; Assert.Equal(propertyDescription, symbol.ToTestDisplayString()); VerifyAccessor(property.GetMethod, getterName); VerifyAccessor(property.SetMethod, setterName); } private static void VerifyAccessor(MethodSymbol? accessor, string? name) { Assert.Equal(name, accessor?.Name); if (accessor is object) { Assert.True(accessor.HasSpecialName); foreach (var parameter in accessor.Parameters) { Assert.Same(accessor, parameter.ContainingSymbol); } } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_42() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public abstract A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname abstract virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { } .property instance class [mscorlib]System.Type modopt(int32) EqualityContract() { .get instance class [mscorlib]System.Type modopt(int32) A::get_EqualityContract() } .property instance object modopt(uint16) P() { .get instance object modopt(uint16) A::get_P() .set instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object modopt(uint16)) } .method family virtual instance class [mscorlib]System.Type modopt(int32) get_EqualityContract() { ldnull ret } .method public abstract virtual instance object modopt(uint16) get_P() { } .method public abstract virtual instance void modopt(uint8) modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object modopt(uint16) 'value') { } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"using static System.Console; record B(object P) : A { static void Main() { B b = new B(3); WriteLine(b.P); WriteLine(((A)b).P); b = new B(1) { P = 2 }; WriteLine(b.P); WriteLine(b.EqualityContract.Name); } }"; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"3 3 2 B").VerifyDiagnostics(); var actualMembers = GetProperties(comp, "B"); Assert.Equal(2, actualMembers.Length); var property = (PropertySymbol)actualMembers[0]; Assert.Equal("System.Type modopt(System.Int32) B.EqualityContract { get; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Int32))); property = (PropertySymbol)actualMembers[1]; Assert.Equal("System.Object modopt(System.UInt16) B.P { get; init; }", property.ToTestDisplayString()); verifyReturnType(property.GetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); verifyReturnType(property.SetMethod, CSharpCustomModifier.CreateRequired(comp.GetWellKnownType(WellKnownType.System_Runtime_CompilerServices_IsExternalInit)), CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Byte))); verifyParameterType(property.SetMethod, CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_UInt16))); static void verifyReturnType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var returnType = method.ReturnTypeWithAnnotations; Assert.True(method.OverriddenMethod.ReturnTypeWithAnnotations.Equals(returnType, TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); AssertEx.Equal(expectedModifiers, returnType.CustomModifiers); } static void verifyParameterType(MethodSymbol method, params CustomModifier[] expectedModifiers) { var parameterType = method.Parameters[0].TypeWithAnnotations; Assert.True(method.OverriddenMethod.Parameters[0].TypeWithAnnotations.Equals(parameterType, TypeCompareKind.ConsiderEverything)); AssertEx.Equal(expectedModifiers, parameterType.CustomModifiers); } } [WorkItem(44618, "https://github.com/dotnet/roslyn/issues/44618")] [Fact] public void Inheritance_43() { var source = @"#nullable enable record A { protected virtual System.Type? EqualityContract => null; } record B : A { static void Main() { var b = new B(); _ = b.EqualityContract.ToString(); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); Assert.Equal("System.Type! B.EqualityContract { get; }", GetProperties(comp, "B").Single().ToTestDisplayString(includeNonNullable: true)); } // No EqualityContract property on base. [Fact] public void Inheritance_44() { var sourceA = @".class public System.Runtime.CompilerServices.IsExternalInit { .method public hidebysig specialname rtspecialname instance void .ctor() { ldnull throw } } .class public A { .method family hidebysig specialname rtspecialname instance void .ctor() { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } .method family hidebysig specialname rtspecialname instance void .ctor(class A A_1) { ldnull throw } .method public hidebysig newslot specialname virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"'() { ldnull throw } .property instance object P() { .get instance object A::get_P() .set instance void modreq(System.Runtime.CompilerServices.IsExternalInit) A::set_P(object) } .method public instance object get_P() { ldnull ret } .method public instance void modreq(System.Runtime.CompilerServices.IsExternalInit) set_P(object 'value') { ret } .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } }"; var refA = CompileIL(sourceA); var sourceB = @"record B : A; "; var comp = CreateCompilation(sourceB, new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0115: 'B.EqualityContract': no suitable method found to override // record B : A; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(1, 8)); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, GetProperties(comp, "B").ToTestDisplayStrings()); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [InlineData(false)] [InlineData(true)] public void CopyCtor(bool useCompilationReference) { var sourceA = @"public record B(object N1, object N2) { }"; var compA = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceA : new[] { sourceA, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); var verifierA = CompileAndVerify(compA, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifierA.VerifyIL("B..ctor(B)", @" { // Code size 31 (0x1f) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object B.<N1>k__BackingField"" IL_000d: stfld ""object B.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object B.<N2>k__BackingField"" IL_0019: stfld ""object B.<N2>k__BackingField"" IL_001e: ret }"); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = @"record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); System.Console.Write("" ""); var c3 = c1 with { P1 = 10, N1 = 30 }; System.Console.Write((c3.P1, c3.P2, c3.N1, c3.N2)); } }"; var compB = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? sourceB : new[] { sourceB, IsExternalInitTypeDefinition }, references: new[] { refA }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe, targetFramework: TargetFramework.StandardLatest); var verifierB = CompileAndVerify(compB, expectedOutput: "(1, 2, 3, 4) (1, 2, 3, 4) (10, 2, 30, 4)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifierB.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); verifierA.VerifyIL($"B.{WellKnownMemberNames.CloneMethodName}()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: newobj ""B..ctor(B)"" IL_0006: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithOtherOverload() { var source = @"public record B(object N1, object N2) { public B(C c) : this(30, 40) => throw null; } public record C(object P1, object P2) : B(3, 4) { static void Main() { var c1 = new C(1, 2); System.Console.Write((c1.P1, c1.P2, c1.N1, c1.N2)); System.Console.Write("" ""); var c2 = c1 with { P1 = 10, P2 = 20, N1 = 30, N2 = 40 }; System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4) (10, 20, 30, 40)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); // call base copy constructor B..ctor(B) verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithObsoleteCopyConstructor() { var source = @"public record B(object N1, object N2) { [System.Obsolete(""Obsolete"", true)] public B(B b) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithParamsCopyConstructor() { var source = @"public record B(object N1, object N2) { public B(B b, params int[] i) : this(30, 40) { } } public record C(object P1, object P2) : B(3, 4) { } "; var comp = CreateCompilation(source); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Object N1, System.Object N2)", "B..ctor(B b, params System.Int32[] i)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 32 (0x20) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithInitializers() { var source = @"public record C(object N1, object N2) { private int field = 42; public int Property = 43; }"; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp, verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics( // (3,17): warning CS0414: The field 'C.field' is assigned but its value is never used // private int field = 42; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field").WithArguments("C.field").WithLocation(3, 17) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 55 (0x37) .maxstack 2 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ldarg.0 IL_0007: ldarg.1 IL_0008: ldfld ""object C.<N1>k__BackingField"" IL_000d: stfld ""object C.<N1>k__BackingField"" IL_0012: ldarg.0 IL_0013: ldarg.1 IL_0014: ldfld ""object C.<N2>k__BackingField"" IL_0019: stfld ""object C.<N2>k__BackingField"" IL_001e: ldarg.0 IL_001f: ldarg.1 IL_0020: ldfld ""int C.field"" IL_0025: stfld ""int C.field"" IL_002a: ldarg.0 IL_002b: ldarg.1 IL_002c: ldfld ""int C.Property"" IL_0031: stfld ""int C.Property"" IL_0036: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_NotInRecordType() { var source = @"public class C { public object Property { get; set; } public int field = 42; public C(C c) { } } public class D : C { public int field2 = 43; public D(D d) : base(d) { } } "; var comp = CreateCompilation(source); var verifier = CompileAndVerify(comp).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int C.field"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: ret }"); verifier.VerifyIL("D..ctor(D)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 43 IL_0003: stfld ""int D.field2"" IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: call ""C..ctor(C)"" IL_000f: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject() { var source = @"public record C(int I) { public int I { get; set; } = 42; public C(C c) { } public static void Main() { var c = new C(1); c.I = 2; var c2 = new C(c); System.Console.Write((c.I, c2.I)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 9 (0x9) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_WithFieldInitializer() { var source = @"public record C(int I) { public int I { get; set; } = 42; public int field = 43; public C(C c) { System.Console.Write("" RAN ""); } public static void Main() { var c = new C(1); c.I = 2; c.field = 100; System.Console.Write((c.I, c.field)); var c2 = new C(c); System.Console.Write((c2.I, c2.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(2, 100) RAN (0, 0)").VerifyDiagnostics( // (1,21): warning CS8907: Parameter 'I' is unread. Did you forget to use it to initialize the property with that name? // public record C(int I) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "I").WithArguments("I").WithLocation(1, 21) ); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr "" RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_GivesParameterToBase() { var source = @" public record C(object I) { public C(C c) : base(1) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("object", "1").WithLocation(4, 21), // (4,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(4, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_DerivesFromObject_WithSomeOtherConstructor() { var source = @" public record C(object I) { public C(int i) : this((object)null) { } public static void Main() { var c = new C((object)null); var c2 = new C(1); var c3 = new C(c); System.Console.Write(""RAN""); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "RAN", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int)", @" { // Code size 10 (0xa) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldnull IL_0002: call ""C..ctor(object)"" IL_0007: nop IL_0008: nop IL_0009: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_DerivesFromObject_UsesThis() { var source = @"public record C(int I) { public C(C c) : this(c.I) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(c.I) Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(3, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_DerivesFromObject_UsesBase() { var source = @"public record C(int I) { public C(C c) : base() { System.Console.Write(""RAN ""); } public static void Main() { var c = new C(1); System.Console.Write(c.I); System.Console.Write("" ""); var c2 = c with { I = 2 }; System.Console.Write(c2.I); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "1 RAN 2", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 20 (0x14) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: nop IL_0008: ldstr ""RAN "" IL_000d: call ""void System.Console.Write(string)"" IL_0012: nop IL_0013: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_NoPositionalMembers() { var source = @"public record B(object N1, object N2) { } public record C(object P1) : B(0, 1) { public C(C c) // 1, 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,12): error CS1729: 'B' does not contain a constructor that takes 0 arguments // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(6, 12), // (6,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) // 1, 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(6, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesThis() { var source = @"public record B(object N1, object N2) { } public record C(object P1, object P2) : B(0, 1) { public C(C c) : this(1, 2) // 1 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : this(1, 2) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "this").WithLocation(6, 21) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButDoesNotDelegateToBaseCopyCtor_UsesBase() { var source = @"public record B(int i) { } public record C(int j) : B(0) { public C(C c) : base(1) // 1 { } } #nullable enable public record D(int j) : B(0) { public D(D? d) : base(1) // 2 { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,21): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) : base(1) // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(6, 21), // (13,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public D(D? d) : base(1) // 2 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(13, 22) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefined_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public D(D d) : base(d) { System.Console.Write(""RAN ""); } public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) RAN (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 21 (0x15) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: nop IL_0009: ldstr ""RAN "" IL_000e: call ""void System.Console.Write(string)"" IL_0013: nop IL_0014: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_Synthesized_WithFieldInitializers() { var source = @"public record C(int I) { } public record D(int J) : C(1) { public int field = 42; public static void Main() { var d = new D(2); System.Console.Write((d.I, d.J, d.field)); System.Console.Write("" ""); var d2 = d with { I = 10, J = 20 }; System.Console.Write((d2.I, d2.J, d.field)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 42) (10, 20, 42)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("D..ctor(D)", @" { // Code size 33 (0x21) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""C..ctor(C)"" IL_0007: nop IL_0008: ldarg.0 IL_0009: ldarg.1 IL_000a: ldfld ""int D.<J>k__BackingField"" IL_000f: stfld ""int D.<J>k__BackingField"" IL_0014: ldarg.0 IL_0015: ldarg.1 IL_0016: ldfld ""int D.field"" IL_001b: stfld ""int D.field"" IL_0020: ret } "); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_UserDefinedButPrivate() { var source = @"public record B(object N1, object N2) { private B(B b) { } } public record C(object P1, object P2) : B(0, 1) { private C(C c) : base(2, 3) { } // 1 } public record D(object P1, object P2) : B(0, 1) { private D(D d) : base(d) { } // 2 } public record E(object P1, object P2) : B(0, 1); // 3 "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,13): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // private B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 13), // (7,13): error CS8878: A copy constructor 'C.C(C)' must be public or protected because the record is not sealed. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "C").WithArguments("C.C(C)").WithLocation(7, 13), // (7,22): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // private C(C c) : base(2, 3) { } // 1 Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "base").WithLocation(7, 22), // (11,13): error CS8878: A copy constructor 'D.D(D)' must be public or protected because the record is not sealed. // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "D").WithArguments("D.D(D)").WithLocation(11, 13), // (11,22): error CS0122: 'B.B(B)' is inaccessible due to its protection level // private D(D d) : base(d) { } // 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(11, 22), // (13,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record E(object P1, object P2) : B(0, 1); // 3 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "E").WithArguments("B").WithLocation(13, 15) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCaller() { var sourceA = @"public record B(object N1, object N2) { internal B(B b) { } }"; var compA = CreateCompilation(sourceA); compA.VerifyDiagnostics( // (3,14): error CS8878: A copy constructor 'B.B(B)' must be public or protected because the record is not sealed. // internal B(B b) { } Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "B").WithArguments("B.B(B)").WithLocation(3, 14) ); var refA = compA.ToMetadataReference(); var sourceB = @" record C(object P1, object P2) : B(3, 4); // 1 "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); compB.VerifyDiagnostics( // (2,8): error CS8867: No accessible copy constructor found in base type 'B'. // record C(object P1, object P2) : B(3, 4); // 1 Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 8) ); var sourceC = @" record C(object P1, object P2) : B(3, 4) { protected C(C c) : base(c) { } // 1, 2 } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9); compC.VerifyDiagnostics( // (4,24): error CS0122: 'B.B(B)' is inaccessible due to its protection level // protected C(C c) : base(c) { } // 1, 2 Diagnostic(ErrorCode.ERR_BadAccess, "base").WithArguments("B.B(B)").WithLocation(4, 24) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleToCallerFromPE_WithIVT() { var sourceA = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""AssemblyB"")] internal record B(object N1, object N2) { public B(B b) { } }"; var compA = CreateCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, assemblyName: "AssemblyA", parseOptions: TestOptions.Regular9); var refA = compA.EmitToImageReference(); var sourceB = @" record C(int j) : B(3, 4); "; var compB = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compB.VerifyDiagnostics(); var sourceC = @" record C(int j) : B(3, 4) { protected C(C c) : base(c) { } } "; var compC = CreateCompilation(sourceC, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB"); compC.VerifyDiagnostics(); var compB2 = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9, assemblyName: "AssemblyB2"); compB2.VerifyEmitDiagnostics( // (2,8): error CS0115: 'C.ToString()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'C.GetHashCode()': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'C.EqualityContract': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'C.Equals(object?)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'C.PrintMembers(StringBuilder)': no suitable method found to override // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C").WithArguments("C.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,19): error CS0122: 'B' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "B").WithArguments("B").WithLocation(2, 19), // (2,20): error CS0122: 'B.B(object, object)' is inaccessible due to its protection level // record C(int j) : B(3, 4); Diagnostic(ErrorCode.ERR_BadAccess, "(3, 4)").WithArguments("B.B(object, object)").WithLocation(2, 20) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButPrivate_InSealedType() { var source = @"public record B(int i) { } public sealed record C(int j) : B(0) { private C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var copyCtor = comp.GetMembers("C..ctor")[1]; Assert.Equal("C..ctor(C c)", copyCtor.ToTestDisplayString()); Assert.True(copyCtor.DeclaredAccessibility == Accessibility.Private); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [WorkItem(45012, "https://github.com/dotnet/roslyn/issues/45012")] public void CopyCtor_UserDefinedButInternal() { var source = @"public record B(object N1, object N2) { } public sealed record Sealed(object P1, object P2) : B(0, 1) { internal Sealed(Sealed s) : base(s) { } } public record Unsealed(object P1, object P2) : B(0, 1) { internal Unsealed(Unsealed s) : base(s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,14): error CS8878: A copy constructor 'Unsealed.Unsealed(Unsealed)' must be public or protected because the record is not sealed. // internal Unsealed(Unsealed s) : base(s) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "Unsealed").WithArguments("Unsealed.Unsealed(Unsealed)").WithLocation(12, 14) ); var sealedCopyCtor = comp.GetMembers("Sealed..ctor")[1]; Assert.Equal("Sealed..ctor(Sealed s)", sealedCopyCtor.ToTestDisplayString()); Assert.True(sealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); var unsealedCopyCtor = comp.GetMembers("Unsealed..ctor")[1]; Assert.Equal("Unsealed..ctor(Unsealed s)", unsealedCopyCtor.ToTestDisplayString()); Assert.True(unsealedCopyCtor.DeclaredAccessibility == Accessibility.Internal); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind() { var source = @"public record B(int i) { public B(ref B b) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,12): error CS8862: A constructor declared in a record with parameter list must have 'this' constructor initializer. // public B(ref B b) => throw null; // 1, not recognized as copy constructor Diagnostic(ErrorCode.ERR_UnexpectedOrMissingConstructorInitializerInRecord, "B").WithLocation(3, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_BaseHasRefKind_WithThisInitializer() { var source = @"public record B(int i) { public B(ref B b) : this(0) => throw null; // 1, not recognized as copy constructor } public record C(int j) : B(1) { protected C(C c) : base(c) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().Where(m => m.Name == ".ctor").ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 i)", "B..ctor(ref B b)", "B..ctor(B original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_WithPrivateField() { var source = @"public record B(object N1, object N2) { private int field1 = 100; public int GetField1() => field1; } public record C(object P1, object P2) : B(3, 4) { private int field2 = 200; public int GetField2() => field2; static void Main() { var c1 = new C(1, 2); var c2 = new C(c1); System.Console.Write((c2.P1, c2.P2, c2.N1, c2.N2, c2.GetField1(), c2.GetField2())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: "(1, 2, 3, 4, 100, 200)", verify: ExecutionConditionUtil.IsCoreClr ? Verification.Skipped : Verification.Fails).VerifyDiagnostics(); verifier.VerifyIL("C..ctor(C)", @" { // Code size 44 (0x2c) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""B..ctor(B)"" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: ldfld ""object C.<P1>k__BackingField"" IL_000e: stfld ""object C.<P1>k__BackingField"" IL_0013: ldarg.0 IL_0014: ldarg.1 IL_0015: ldfld ""object C.<P2>k__BackingField"" IL_001a: stfld ""object C.<P2>k__BackingField"" IL_001f: ldarg.0 IL_0020: ldarg.1 IL_0021: ldfld ""int C.field2"" IL_0026: stfld ""int C.field2"" IL_002b: ret }"); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_MissingInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Removed copy constructor //.method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); var source2 = @" public record C : B { public C(C c) { } }"; var comp2 = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp2.VerifyDiagnostics( // (4,12): error CS8868: A copy constructor in a record must call a copy constructor of the base, or a parameterless object constructor if the record inherits from object. // public C(C c) { } Diagnostic(ErrorCode.ERR_CopyConstructorMustInvokeBaseCopyConstructor, "C").WithLocation(4, 12) ); } [Fact, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] public void CopyCtor_InaccessibleInMetadata() { // IL for `public record B { }` var ilSource = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals ( object '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } // Inaccessible copy constructor .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) ); } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata() { // IL for a minimal `public record B { }` with injected copy constructors var ilSource_template = @" .class public auto ansi beforefieldinit B extends [mscorlib]System.Object { INJECT .method public hidebysig specialname newslot virtual instance class B '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void B::.ctor(class B) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C : B { public static void Main() { var c = new C(); _ = c with { }; } }"; // We're going to inject various copy constructors into record B (at INJECT marker), and check which one is used // by derived record C // The RAN and THROW markers are shorthands for method bodies that print "RAN" and throw, respectively. // .ctor(B) vs. .ctor(modopt B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW "); // .ctor(modopt B) alone verify(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN "); // .ctor(B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(modopt B) vs. .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int64) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW "); // .ctor(B) vs. .ctor(modopt1 B) and .ctor(modreq B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modreq(int32) '' ) cil managed THROW "); // .ctor(modeopt1 B) vs. .ctor(modopt2 B) verifyBoth(@" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); // private .ctor(B) vs. .ctor(modopt1 B) and .ctor(modopt B) verifyBoth(@" .method private hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed RAN ", @" .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int64) '' ) cil managed THROW .method public hidebysig specialname rtspecialname instance void .ctor ( class B modopt(int32) '' ) cil managed THROW ", isError: true); void verifyBoth(string inject1, string inject2, bool isError = false) { verify(inject1 + inject2, isError); verify(inject2 + inject1, isError); } void verify(string inject, bool isError = false) { var ranBody = @" { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } "; var throwBody = @" { IL_0000: ldnull IL_0001: throw } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource_template.Replace("INJECT", inject).Replace("RAN", ranBody).Replace("THROW", throwBody), parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); var expectedDiagnostics = isError ? new[] { // (2,15): error CS8867: No accessible copy constructor found in base type 'B'. // public record C : B Diagnostic(ErrorCode.ERR_NoCopyConstructorInBaseType, "C").WithArguments("B").WithLocation(2, 15) } : new DiagnosticDescription[] { }; comp.VerifyDiagnostics(expectedDiagnostics); if (expectedDiagnostics is null) { CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } } } [Fact, WorkItem(45077, "https://github.com/dotnet/roslyn/issues/45077")] public void CopyCtor_AmbiguitiesInMetadata_GenericType() { // IL for a minimal `public record B<T> { }` with modopt in nested position of parameter type var ilSource = @" .class public auto ansi beforefieldinit B`1<T> extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class B`1<!T>> { .method family hidebysig specialname rtspecialname instance void .ctor ( class B`1<!T modopt(int64)> '' ) cil managed { IL_0000: ldstr ""RAN"" IL_0005: call void [mscorlib]System.Console::WriteLine(string) IL_000a: ret } .method public hidebysig specialname newslot virtual instance class B`1<!T> '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { IL_0000: ldarg.0 IL_0001: newobj instance void class B`1<!T>::.ctor(class B`1<!0>) IL_0006: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } .method public newslot virtual instance bool Equals ( class B`1<!T> '' ) cil managed { IL_0000: ldnull IL_0001: throw } .method family virtual instance class [mscorlib]System.Type get_EqualityContract() { ldnull ret } .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B`1::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } "; var source = @" public record C<T> : B<T> { } public class Program { public static void Main() { var c = new C<string>(); _ = c with { }; } }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void CopyCtor_Accessibility_01(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,6): error CS8878: A copy constructor 'A.A(A)' must be public or protected because the record is not sealed. // A(A a) Diagnostic(ErrorCode.ERR_CopyConstructorWrongAccessibility, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); } [Theory] [InlineData("public")] [InlineData("protected")] public void CopyCtor_Accessibility_02(string accessibility) { var source = $@" record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("internal")] [InlineData("public")] public void CopyCtor_Accessibility_03(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("private protected")] [InlineData("internal protected")] [InlineData("protected")] public void CopyCtor_Accessibility_04(string accessibility) { var source = $@" sealed record A(int X) {{ { accessibility } A(A a) => System.Console.Write(""RAN""); public static void Main() {{ var a = new A(123); _ = a with {{}}; }} }} "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "RAN").VerifyDiagnostics( // (4,15): warning CS0628: 'A.A(A)': new protected member declared in sealed type // protected A(A a) Diagnostic(ErrorCode.WRN_ProtectedInSealed, "A").WithArguments("A.A(A)").WithLocation(4, 6 + accessibility.Length) ); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void CopyCtor_Signature_01() { var source = @" record A(int X) { public A(in A a) : this(-15) => System.Console.Write(""RAN""); public static void Main() { var a = new A(123); System.Console.Write((a with { }).X); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: "123").VerifyDiagnostics(); } [Fact] public void Deconstruct_Simple() { var source = @"using System; record B(int X, int Y) { public static void Main() { M(new B(1, 2)); } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); var deconstruct = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("B.Deconstruct"); Assert.Equal(2, deconstruct.ParameterCount); Assert.Equal(RefKind.Out, deconstruct.Parameters[0].RefKind); Assert.Equal("X", deconstruct.Parameters[0].Name); Assert.Equal(RefKind.Out, deconstruct.Parameters[1].RefKind); Assert.Equal("Y", deconstruct.Parameters[1].Name); Assert.True(deconstruct.ReturnsVoid); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsStatic); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); } [Fact] public void Deconstruct_PositionalAndNominalProperty() { var source = @"using System; record B(int X) { public int Y { get; init; } public static void Main() { M(new B(1)); } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } }"; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Nested() { var source = @"using System; record B(int X, int Y); record C(B B, int Z) { public static void Main() { M(new C(new B(1, 2), 3)); } static void M(C c) { switch (c) { case C(B(int x, int y), int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); verifier.VerifyIL("B.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int B.X.get"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int B.Y.get"" IL_000f: stind.i4 IL_0010: ret }"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""B C.B.get"" IL_0007: stind.ref IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: call ""int C.Z.get"" IL_000f: stind.i4 IL_0010: ret }"); } [Fact] public void Deconstruct_PropertyCollision() { var source = @"using System; record B(int X, int Y) { public int X => 3; static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "32"); verifier.VerifyDiagnostics( // (3,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(3, 14) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_01() { var source = @" record B(int X, int Y) { public int X() => 3; static void M(B b) { switch (b) { case B(int x, int y): break; } } static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'B' already contains a definition for 'X' // public int X() => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("B", "X").WithLocation(4, 16) ); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_02() { var source = @" record B { public int X(int y) => y; } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_03() { var source = @" using System; record B { public int X() => 3; } record C(int X, int Y) : B { public new int X { get; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "02"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_MethodCollision_04() { var source = @" record C(int X, int Y) { public int X(int arg) => 3; static void M(C c) { switch (c) { case C(int x, int y): break; } } static void Main() { M(new C(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,16): error CS0102: The type 'C' already contains a definition for 'X' // public int X(int arg) => 3; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(4, 16) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_FieldCollision() { var source = @" using System; record C(int X) { int X; static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(0)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (4,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record C(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(4, 10), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (6,9): warning CS0169: The field 'C.X' is never used // int X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("C.X").WithLocation(6, 9) ); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_EventCollision() { var source = @" using System; record C(Action X) { event Action X; static void M(C c) { switch (c) { case C(Action x): Console.Write(x); break; } } static void Main() { M(new C(() => { })); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): error CS0102: The type 'C' already contains a definition for 'X' // event Action X; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "X").WithArguments("C", "X").WithLocation(6, 18), // (6,18): warning CS0067: The event 'C.X' is never used // event Action X; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "X").WithArguments("C.X").WithLocation(6, 18) ); Assert.Equal( "void C.Deconstruct(out System.Action X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_WriteOnlyPropertyInBase() { var source = @" using System; record B { public int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,14): error CS8866: Record member 'B.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X) : B Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("B.X", "int", "X").WithLocation(9, 14), // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14)); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_PrivateWriteOnlyPropertyInBase() { var source = @" using System; record B { private int X { set { } } } record C(int X) : B { static void M(C c) { switch (c) { case C(int x): Console.Write(x); break; } } static void Main() { M(new C(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal( "void C.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty() { var source = @" record C { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Inheritance_01() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Null(comp.GetMember("C.Deconstruct")); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_02() { var source = @" using System; record B(int X, int Y) { // https://github.com/dotnet/roslyn/issues/44902 internal B() : this(0, 1) { } } record C(int X, int Y, int Z) : B(X, Y) { static void M(C c) { switch (c) { case C(int x, int y, int z): Console.Write(x); Console.Write(y); Console.Write(z); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "01201"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y, out System.Int32 Z)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_03() { var source = @" using System; record B(int X, int Y) { internal B() : this(0, 1) { } } record C(int X, int Y) : B { static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } switch (c) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0101"); verifier.VerifyDiagnostics( // (9,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(9, 14), // (9,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(9, 21) ); var comp = verifier.Compilation; Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Inheritance_04() { var source = @" using System; record A<T>(T P) { internal A() : this(default(T)) { } } record B1(int P, object Q) : A<int>(P) { internal B1() : this(0, null) { } } record B2(object P, object Q) : A<object>(P) { internal B2() : this(null, null) { } } record B3<T>(T P, object Q) : A<T>(P) { internal B3() : this(default, 0) { } } class C { static void M0(A<int> arg) { switch (arg) { case A<int>(int x): Console.Write(x); break; } } static void M1(B1 arg) { switch (arg) { case B1(int p, object q): Console.Write(p); Console.Write(q); break; } } static void M2(B2 arg) { switch (arg) { case B2(object p, object q): Console.Write(p); Console.Write(q); break; } } static void M3(B3<int> arg) { switch (arg) { case B3<int>(int p, object q): Console.Write(p); Console.Write(q); break; } } static void Main() { M0(new A<int>(0)); M1(new B1(1, 2)); M2(new B2(3, 4)); M3(new B3<int>(5, 6)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "0123456"); verifier.VerifyDiagnostics(); var comp = verifier.Compilation; Assert.Equal( "void A<T>.Deconstruct(out T P)", comp.GetMember("A.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B1.Deconstruct(out System.Int32 P, out System.Object Q)", comp.GetMember("B1.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B2.Deconstruct(out System.Object P, out System.Object Q)", comp.GetMember("B2.Deconstruct").ToTestDisplayString(includeNonNullable: false)); Assert.Equal( "void B3<T>.Deconstruct(out T P, out System.Object Q)", comp.GetMember("B3.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_01() { var source = @" using System; record C(int X, int Y) { public long X { get; init; } public long Y { get; init; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(0, 1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,14): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "int", "X").WithLocation(4, 14), // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (4,21): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record C(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void C.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_02() { var source = @" #nullable enable using System; record C(string? X, string Y) { public string X { get; init; } = null!; public string? Y { get; init; } static void M(C c) { switch (c) { case C(var x, string y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(""a"", ""b"")); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(5, 18), // (5,28): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(string? X, string Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(5, 28) ); Assert.Equal( "void C.Deconstruct(out System.String? X, out System.String Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Conversion_03() { var source = @" using System; class Base { } class Derived : Base { } record C(Derived X, Base Y) { public Base X { get; init; } public Derived Y { get; init; } static void M(C c) { switch (c) { case C(Derived x, Base y): Console.Write(x); Console.Write(y); break; } } static void Main() { M(new C(new Derived(), new Base())); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,18): error CS8866: Record member 'C.X' must be a readable instance property or field of type 'Derived' to match positional parameter 'X'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("C.X", "Derived", "X").WithLocation(7, 18), // (7,18): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 18), // (7,26): error CS8866: Record member 'C.Y' must be a readable instance property or field of type 'Base' to match positional parameter 'Y'. // record C(Derived X, Base Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("C.Y", "Base", "Y").WithLocation(7, 26), // (7,26): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(Derived X, Base Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 26)); Assert.Equal( "void C.Deconstruct(out Derived X, out Base Y)", comp.GetMember("C.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_Empty_WithParameterList() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // case C(): Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "()").WithArguments("C", "Deconstruct").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); Assert.Null(comp.GetMember("C.Deconstruct")); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_01() { var source = @"using System; record C() { public void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_02() { var source = @"using System; record C() { public void Deconstruct(out int X, out int Y) { X = 1; Y = 2; } static void M(C c) { switch (c) { case C(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_03() { var source = @"using System; record C() { private void Deconstruct() { } static void M(C c) { switch (c) { case C(): Console.Write(12); break; } } public static void Main() { M(new C()); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_04() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public static void Deconstruct() { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS0176: Member 'C.Deconstruct()' cannot be accessed with an instance reference; qualify it with a type name instead // case C(): Diagnostic(ErrorCode.ERR_ObjectProhibited, "()", isSuppressed: false).WithArguments("C.Deconstruct()").WithLocation(8, 19), // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_Empty_WithParameterList_UserDefined_05() { var source = @" record C() { static void M(C c) { switch (c) { case C(): break; } } static void Main() { M(new C()); } public int Deconstruct() { return 1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 0 out parameters and a void return type. // case C(): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "()").WithArguments("C", "0").WithLocation(8, 19)); } [Fact] public void Deconstruct_UserDefined() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int X, out int Y) { X = this.X + 1; Y = this.Y + 2; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(0, 0)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_01() { var source = @"using System; record B(int X, int Y) { public void Deconstruct(out int Z) { Z = X + Y; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } switch (b) { case B(int z): Console.Write(z); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "123"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", "void B.Deconstruct(out System.Int32 Z)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_02() { var source = @"using System; record B(int X) { public int Deconstruct(out int a) => throw null; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,16): error CS8874: Record member 'B.Deconstruct(out int)' must return 'void'. // public int Deconstruct(out int a) => throw null; Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Deconstruct").WithArguments("B.Deconstruct(out int)", "void").WithLocation(5, 16), // (11,19): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'B', with 1 out parameters and a void return type. // case B(int x): Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(int x)").WithArguments("B", "1").WithLocation(11, 19)); Assert.Equal("System.Int32 B.Deconstruct(out System.Int32 a)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_03() { var source = @"using System; record B(int X) { public void Deconstruct(int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); var expectedSymbols = new[] { "void B.Deconstruct(out System.Int32 X)", "void B.Deconstruct(System.Int32 X)", }; Assert.Equal(expectedSymbols, verifier.Compilation.GetMembers("B.Deconstruct").Select(s => s.ToTestDisplayString(includeNonNullable: false))); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_04() { var source = @"using System; record B(int X) { public void Deconstruct(ref int X) { } static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0663: 'B' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public void Deconstruct(ref int X) Diagnostic(ErrorCode.ERR_OverloadRefKind, "Deconstruct").WithArguments("B", "method", "ref", "out").WithLocation(5, 17) ); Assert.Equal(2, comp.GetMembers("B.Deconstruct").Length); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_05() { var source = @"using System; record A(int X) { public A() : this(0) { } public int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact] public void Deconstruct_UserDefined_DifferentSignature_06() { var source = @"using System; record A(int X) { public A() : this(0) { } public virtual int Deconstruct(out int a, out int b) => throw null; } record B(int X, int Y) : A(X) { static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "12"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData("")] [InlineData("private")] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void Deconstruct_UserDefined_Accessibility_07(string accessibility) { var source = $@" record A(int X) {{ { accessibility } void Deconstruct(out int a) => throw null; }} "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,11): error CS8873: Record member 'A.Deconstruct(out int)' must be public. // void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 11 + accessibility.Length) ); } [Fact] public void Deconstruct_UserDefined_Static_08() { var source = @" record A(int X) { public static void Deconstruct(out int a) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS8877: Record member 'A.Deconstruct(out int)' may not be static. // public static void Deconstruct(out int a) Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Deconstruct").WithArguments("A.Deconstruct(out int)").WithLocation(4, 24) ); } [Fact] public void Deconstruct_Shadowing_01() { var source = @" abstract record A(int X) { public abstract int Deconstruct(out int a, out int b); } abstract record B(int X, int Y) : A(X) { public static void Main() { } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (6,17): error CS0533: 'B.Deconstruct(out int, out int)' hides inherited abstract member 'A.Deconstruct(out int, out int)' // abstract record B(int X, int Y) : A(X) Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Deconstruct(out int, out int)", "A.Deconstruct(out int, out int)").WithLocation(6, 17) ); } [Fact] public void Deconstruct_TypeMismatch_01() { var source = @" record A(int X) { public System.Type X => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14) ); } [Fact] public void Deconstruct_TypeMismatch_02() { var source = @" record A { public System.Type X => throw null; } record B(int X) : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (7,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record B(int X) : A; Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(7, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X) : A; Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45010")] [WorkItem(45010, "https://github.com/dotnet/roslyn/issues/45010")] public void Deconstruct_ObsoleteProperty() { var source = @"using System; record B(int X) { [Obsolete] int X { get; } = X; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "1"); verifier.VerifyDiagnostics(); Assert.Equal("void B.Deconstruct(out System.Int32 X)", verifier.Compilation.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/45009")] [WorkItem(45009, "https://github.com/dotnet/roslyn/issues/45009")] public void Deconstruct_RefProperty() { var source = @"using System; record B(int X) { static int _x = 2; ref int X => ref _x; static void M(B b) { switch (b) { case B(int x): Console.Write(x); break; } } public static void Main() { M(new B(1)); } } "; var verifier = CompileAndVerify(source, expectedOutput: "2"); verifier.VerifyDiagnostics(); var deconstruct = verifier.Compilation.GetMember("B.Deconstruct"); Assert.Equal("void B.Deconstruct(out System.Int32 X)", deconstruct.ToTestDisplayString(includeNonNullable: false)); Assert.Equal(Accessibility.Public, deconstruct.DeclaredAccessibility); Assert.False(deconstruct.IsAbstract); Assert.False(deconstruct.IsVirtual); Assert.False(deconstruct.IsOverride); Assert.False(deconstruct.IsSealed); Assert.True(deconstruct.IsImplicitlyDeclared); } [Fact] public void Deconstruct_Static() { var source = @" using System; record B(int X, int Y) { static int Y { get; } static void M(B b) { switch (b) { case B(int x, int y): Console.Write(x); Console.Write(y); break; } } public static void Main() { M(new B(1, 2)); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,21): error CS8866: Record member 'B.Y' must be a readable instance property or field of type 'int' to match positional parameter 'Y'. // record B(int X, int Y) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Y").WithArguments("B.Y", "int", "Y").WithLocation(4, 21), // (4,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(4, 21)); Assert.Equal( "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)", comp.GetMember("B.Deconstruct").ToTestDisplayString(includeNonNullable: false)); } [Theory] [InlineData(false)] [InlineData(true)] public void Overrides_01(bool usePreview) { var source = @"record A { public sealed override bool Equals(object other) => false; public sealed override int GetHashCode() => 0; public sealed override string ToString() => null; } record B(int X, int Y) : A { }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: usePreview ? TestOptions.Regular10 : TestOptions.Regular9); if (usePreview) { comp.VerifyDiagnostics( // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } else { comp.VerifyDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32), // (5,35): error CS8773: Feature 'sealed ToString in record' is not available in C# 9.0. Please use language version 10.0 or greater. // public sealed override string ToString() => null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "ToString").WithArguments("sealed ToString in record", "10.0").WithLocation(5, 35), // (3,33): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public sealed override bool Equals(object other) => false; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 33), // (7,8): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(7, 8) ); } var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", "A B." + WellKnownMemberNames.CloneMethodName + "()", "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Overrides_02() { var source = @"abstract record A { public abstract override bool Equals(object other); public abstract override int GetHashCode(); public abstract override string ToString(); } record B(int X, int Y) : A { }"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? source : new[] { source, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (3,35): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public abstract override bool Equals(object other); Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 35), // (7,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(object)' // record B(int X, int Y) : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(object)").WithLocation(7, 8) ); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B..ctor(System.Int32 X, System.Int32 Y)", "System.Type B.EqualityContract.get", "System.Type B.EqualityContract { get; }", "System.Int32 B.<X>k__BackingField", "System.Int32 B.X.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.X.init", "System.Int32 B.X { get; init; }", "System.Int32 B.<Y>k__BackingField", "System.Int32 B.Y.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B.Y.init", "System.Int32 B.Y { get; init; }", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "void B.Deconstruct(out System.Int32 X, out System.Int32 Y)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void ObjectEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public final hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.Equals(object?)' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.Equals(object?)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(object?)': cannot override inherited member 'A.Equals(object)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(object?)", "A.Equals(object)").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public newslot hidebysig virtual instance int32 Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(object?)': return type must be 'int' to match overridden member 'A.Equals(object)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(object?)", "A.Equals(object)", "int").WithLocation(2, 15) ); } [Fact] public void ObjectEquals_05() { var source0 = @"namespace System { public class Object { public virtual int Equals(object other) => default; public virtual int GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.Equals(object?)': return type must be 'int' to match overridden member 'object.Equals(object)' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.Equals(object?)", "object.Equals(object)", "int").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectEquals_06() { var source = @"record A { public static new bool Equals(object obj) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,28): error CS0111: Type 'A' already defines a member called 'Equals' with the same parameter types // public static new bool Equals(object obj) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "A").WithLocation(3, 28) ); } [Fact] public void ObjectGetHashCode_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var source2 = @" public record B : A { public override int GetHashCode() => 0; }"; var source3 = @" public record C : B { } "; var source4 = @" public record C : B { public override int GetHashCode() => 0; } "; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source1 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source1 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public record B : A { Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "B").WithArguments("B.GetHashCode()").WithLocation(2, 15) ); comp = CreateCompilationWithIL(new[] { source2 + source3, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); comp = CreateCompilationWithIL(new[] { source2 + source4, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override int GetHashCode() => 0; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source1 = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source1, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance bool GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0508: 'B.GetHashCode()': return type must be 'bool' to match overridden member 'A.GetHashCode()' // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "bool").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_04() { var source = @"record A { public override bool GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,26): error CS0508: 'A.GetHashCode()': return type must be 'int' to match overridden member 'object.GetHashCode()' // public override bool GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GetHashCode").WithArguments("A.GetHashCode()", "object.GetHashCode()", "int").WithLocation(3, 26) ); } [Fact] public void ObjectGetHashCode_05() { var source = @"record A { public new int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_06() { var source = @"record A { public static new int GetHashCode() => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,27): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public static new int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 27), // (6,8): error CS0506: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(6, 8) ); } [Fact] public void ObjectGetHashCode_07() { var source = @"record A { public new int GetHashCode => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,20): error CS0102: The type 'A' already contains a definition for 'GetHashCode' // public new int GetHashCode => throw null; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "GetHashCode").WithArguments("A", "GetHashCode").WithLocation(3, 20) ); } [Fact] public void ObjectGetHashCode_08() { var source = @"record A { public new void GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,21): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public new void GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 21) ); } [Fact] public void ObjectGetHashCode_09() { var source = @"record A { public void GetHashCode(int x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); Assert.Equal("System.Int32 A.GetHashCode()", comp.GetMembers("A.GetHashCode").First().ToTestDisplayString()); } [Fact] public void ObjectGetHashCode_10() { var source = @" record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS8870: 'A.GetHashCode()' cannot be sealed because containing record is not sealed. // public sealed override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_SealedAPIInRecord, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(4, 32) ); } [Fact] public void ObjectGetHashCode_11() { var source = @" sealed record A { public sealed override int GetHashCode() => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void ObjectGetHashCode_12() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public final hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideSealed, "B").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(2, 15) ); var source2 = @" public record B : A { public override int GetHashCode() => throw null; }"; comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,25): error CS0239: 'B.GetHashCode()': cannot override inherited member 'A.GetHashCode()' because it is sealed // public override int GetHashCode() => throw null; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()").WithLocation(3, 25) ); } [Fact] public void ObjectGetHashCode_13() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override A GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8869: 'B.GetHashCode()' does not override expected method from 'object'. // public override A GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("B.GetHashCode()").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot hidebysig virtual instance class A GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source2 = @" public record B : A { public override B GetHashCode() => default; }"; var comp = CreateCompilationWithIL(new[] { source2, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,23): error CS8830: 'B.GetHashCode()': Target runtime doesn't support covariant return types in overrides. Return type must be 'A' to match overridden member 'A.GetHashCode()' // public override B GetHashCode() => default; Diagnostic(ErrorCode.ERR_RuntimeDoesNotSupportCovariantReturnsOfClasses, "GetHashCode").WithArguments("B.GetHashCode()", "A.GetHashCode()", "A").WithLocation(3, 23) ); } [Fact] public void ObjectGetHashCode_15() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual Something GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } public class Something { } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override Something GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,31): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override Something GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 31), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override Something GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_16() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { public override bool GetHashCode() => default; } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (3,26): error CS8869: 'A.GetHashCode()' does not override expected method from 'object'. // public override bool GetHashCode() => default; Diagnostic(ErrorCode.ERR_DoesNotOverrideMethodFromObject, "GetHashCode").WithArguments("A.GetHashCode()").WithLocation(3, 26), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Exception").WithLocation(2, 1), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { public override bool GetHashCode() => default; }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void ObjectGetHashCode_17() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual bool GetHashCode() => default; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Char { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(char c) => null; public StringBuilder Append(object o) => null; } } "; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @" public record A { } "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'A.GetHashCode()': return type must be 'bool' to match overridden member 'object.GetHashCode()' // public record A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "A").WithArguments("A.GetHashCode()", "object.GetHashCode()", "bool").WithLocation(2, 15), // (2,15): error CS0518: Predefined type 'System.Type' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 15), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Exception' is not defined or imported // public record A { Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"public record A { }").WithArguments("System.Exception").WithLocation(2, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // 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), // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // public record A { Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"public record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1) ); } [Fact] public void BaseEquals_01() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_02() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(2, 15) ); } [Fact] public void BaseEquals_03() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance int32 Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0508: 'B.Equals(A?)': return type must be 'int' to match overridden member 'A.Equals(A)' // public record B : A { Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "B").WithArguments("B.Equals(A?)", "A.Equals(A)", "int").WithLocation(2, 15) ); } [Fact] public void BaseEquals_04() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type B::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { }"; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8871: 'C.Equals(B?)' does not override expected method from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseMethod, "C").WithArguments("C.Equals(B?)", "B").WithLocation(2, 15) ); } [Fact] public void BaseEquals_05() { var source = @" record A { } record B : A { public override bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,26): error CS0111: Type 'B' already defines a member called 'Equals' with the same parameter types // public override bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Equals").WithArguments("Equals", "B").WithLocation(8, 26) ); } [Fact] public void RecordEquals_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(A x); } record B : A { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (5,26): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public abstract bool Equals(A x); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 26), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); } [Fact] public void RecordEquals_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,26): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 26) ); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,33): error CS8872: 'B.Equals(B)' must allow overriding because the containing record is not sealed. // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("B.Equals(B)").WithLocation(9, 33), // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); } [Fact] public void RecordEquals_04() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } sealed record B : A { public sealed override bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(B) False ").VerifyDiagnostics( // (9,33): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public sealed override bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 33) ); var copyCtor = comp.GetMember<NamedTypeSymbol>("A").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Protected, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); copyCtor = comp.GetMember<NamedTypeSymbol>("B").InstanceConstructors.Where(c => c.ParameterCount == 1).Single(); Assert.Equal(Accessibility.Private, copyCtor.DeclaredAccessibility); Assert.False(copyCtor.IsOverride); Assert.False(copyCtor.IsVirtual); Assert.False(copyCtor.IsAbstract); Assert.False(copyCtor.IsSealed); Assert.True(copyCtor.IsImplicitlyDeclared); } [Fact] public void RecordEquals_05() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } abstract record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,17): error CS0533: 'B.Equals(B?)' hides inherited abstract member 'A.Equals(B)' // abstract record B : A Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "B").WithArguments("B.Equals(B?)", "A.Equals(B)").WithLocation(7, 17) ); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_06(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(B x); } " + modifiers + @" record B : A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (8,8): error CS0534: 'B' does not implement inherited abstract member 'A.Equals(B)' // record B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.Equals(B)").WithLocation(8, 8) ); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_07(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_08(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public abstract bool Equals(C x); } abstract record B : A { public override bool Equals(C x) => Report(""B.Equals(C)""); } " + modifiers + @" record C : B { } class Program { static void Main() { A a1 = new C(); C c2 = new C(); System.Console.WriteLine(a1.Equals(c2)); System.Console.WriteLine(c2.Equals(a1)); System.Console.WriteLine(c2.Equals((C)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.Equals(C) False True True ").VerifyDiagnostics(); var clone = comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.True(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); clone = comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.True(clone.IsOverride); Assert.False(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Theory] [InlineData("")] [InlineData("sealed ")] public void RecordEquals_09(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public bool Equals(B x) => Report(""A.Equals(B)""); } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" A.Equals(B) False True True ").VerifyDiagnostics(); } [Theory] [InlineData("protected")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void RecordEquals_10(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void RecordEquals_11(string accessibility) { var source = $@" record A {{ { accessibility } virtual bool Equals(A x) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.Equals(A)': virtual or abstract members cannot be private // virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_VirtualPrivate, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): error CS8873: Record member 'A.Equals(A)' must be public. // { accessibility } virtual bool Equals(A x) Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 19 + accessibility.Length), // (4,...): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // virtual bool Equals(A x) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 19 + accessibility.Length) ); } [Fact] public void RecordEquals_12() { var source = @" record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } public virtual bool Equals(B other) => Report(""A.Equals(B)""); } class B { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a1.Equals((object)a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_13() { var source = @" record A { public virtual int Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,24): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual int Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual int Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void RecordEquals_14() { var source = @" record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(SpecialType.System_Boolean); comp.VerifyEmitDiagnostics( // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,1): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, @"record A { public virtual bool Equals(A other) => throw null; System.Boolean System.IEquatable<A>.Equals(A x) => throw null; }").WithArguments("System.Boolean").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Boolean' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Boolean").WithLocation(2, 8), // (4,20): error CS0518: Predefined type 'System.Boolean' is not defined or imported // public virtual bool Equals(A other) Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "bool").WithArguments("System.Boolean").WithLocation(4, 20), // (4,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 25) ); } [Fact] public void RecordEquals_15() { var source = @" record A { public virtual Boolean Equals(A other) => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,20): error CS0246: The type or namespace name 'Boolean' could not be found (are you missing a using directive or an assembly reference?) // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Boolean").WithArguments("Boolean").WithLocation(4, 20), // (4,28): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual Boolean Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 28) ); } [Fact] public void RecordEquals_16() { var source = @" abstract record A { } record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.True(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_17() { var source = @" abstract record A { } sealed record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("B.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean B.Equals(B? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_18() { var source = @" sealed record A { } class Program { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); System.Console.WriteLine(a2.Equals(a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True ").VerifyDiagnostics(); var recordEquals = comp.GetMembers("A.Equals").OfType<SynthesizedRecordEquals>().Single(); Assert.Equal("System.Boolean A.Equals(A? other)", recordEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, recordEquals.DeclaredAccessibility); Assert.False(recordEquals.IsAbstract); Assert.False(recordEquals.IsVirtual); Assert.False(recordEquals.IsOverride); Assert.False(recordEquals.IsSealed); Assert.True(recordEquals.IsImplicitlyDeclared); } [Fact] public void RecordEquals_19() { var source = @" record A { public static bool Equals(A x) => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24), // (7,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(7, 8) ); } [Fact] public void RecordEquals_20() { var source = @" sealed record A { public static bool Equals(A x) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,15): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // sealed record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 15), // (4,24): error CS8877: Record member 'A.Equals(A)' may not be static. // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A x) => throw null; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityContract_01() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Fact] public void EqualityContract_02() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (9,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(9, 43) ); } [Fact] public void EqualityContract_03() { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected abstract System.Type EqualityContract { get; } } sealed record B : A { protected sealed override System.Type EqualityContract { get { Report(""B.EqualityContract""); return typeof(B); } } } class Program { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" B.EqualityContract B.EqualityContract True ").VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("sealed ")] public void EqualityContract_04(string modifiers) { var source = @" abstract record A { internal static bool Report(string s) { System.Console.WriteLine(s); return false; } protected virtual System.Type EqualityContract { get { Report(""A.EqualityContract""); return typeof(B); } } } " + modifiers + @" record B : A { } class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @" True True True ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); } [Theory] [InlineData("public")] [InlineData("internal")] [InlineData("private protected")] [InlineData("internal protected")] public void EqualityContract_05(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("private")] public void EqualityContract_06(string accessibility) { var source = $@" record A {{ { accessibility } virtual System.Type EqualityContract => throw null; bool System.IEquatable<A>.Equals(A x) => throw null; }} "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,...): error CS0621: 'A.EqualityContract': virtual or abstract members cannot be private // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_VirtualPrivate, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length), // (4,...): error CS8875: Record member 'A.EqualityContract' must be protected. // { accessibility } virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonProtectedAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 26 + accessibility.Length) ); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_07(string modifiers) { var source = @" record A { } " + modifiers + @" record B : A { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { A a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.False(equalityContractGet.IsVirtual); Assert.True(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Theory] [InlineData("")] [InlineData("abstract ")] [InlineData("sealed ")] public void EqualityContract_08(string modifiers) { var source = modifiers + @" record B { public void PrintEqualityContract() => System.Console.WriteLine(EqualityContract); } "; if (modifiers != "abstract ") { source += @" class Program { static void Main() { B a1 = new B(); B b2 = new B(); System.Console.WriteLine(a1.Equals(b2)); System.Console.WriteLine(b2.Equals(a1)); System.Console.WriteLine(b2.Equals((B)a1)); b2.PrintEqualityContract(); } }"; } var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: modifiers == "abstract " ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: modifiers == "abstract " ? null : @" True True True B ").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); var equalityContractGet = equalityContract.GetMethod; Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(modifiers == "sealed " ? Accessibility.Private : Accessibility.Protected, equalityContractGet!.DeclaredAccessibility); Assert.False(equalityContractGet.IsAbstract); Assert.Equal(modifiers != "sealed ", equalityContractGet.IsVirtual); Assert.False(equalityContractGet.IsOverride); Assert.False(equalityContractGet.IsSealed); Assert.True(equalityContractGet.IsImplicitlyDeclared); Assert.Empty(equalityContractGet.DeclaringSyntaxReferences); verifier.VerifyIL("B.EqualityContract.get", @" { // Code size 11 (0xb) .maxstack 1 IL_0000: ldtoken ""B"" IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)"" IL_000a: ret } "); } [Fact] public void EqualityContract_09() { var source = @" record A { protected virtual int EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27) ); } [Fact] public void EqualityContract_10() { var source = @" record A { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeTypeMissing(WellKnownType.System_Type); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Type.GetTypeFromHandle' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "GetTypeFromHandle").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Type.op_Equality' // record A Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record A { }").WithArguments("System.Type", "op_Equality").WithLocation(2, 1), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8) ); } [Fact] public void EqualityContract_11() { var source = @" record A { protected virtual Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(4, 23) ); } [Fact] public void EqualityContract_12() { var source = @" record A { protected System.Type EqualityContract => throw null; } sealed record B { protected System.Type EqualityContract => throw null; } sealed record C { protected virtual System.Type EqualityContract => throw null; } record D { protected virtual System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 27), // (10,27): warning CS0628: 'B.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (10,27): error CS8879: Record member 'B.EqualityContract' must be private. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(10, 27), // (11,12): warning CS0628: 'B.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("B.EqualityContract.get").WithLocation(11, 12), // (16,35): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (16,35): error CS8879: Record member 'C.EqualityContract' must be private. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(16, 35), // (17,12): error CS0549: 'C.EqualityContract.get' is a new virtual member in sealed type 'C' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("C.EqualityContract.get", "C").WithLocation(17, 12) ); } [Fact] public void EqualityContract_13() { var source = @" record A {} record B : A { protected System.Type EqualityContract => throw null; } sealed record C : A { protected System.Type EqualityContract => throw null; } sealed record D : A { protected virtual System.Type EqualityContract => throw null; } record E : A { protected virtual System.Type EqualityContract => throw null; } record F : A { protected override System.Type EqualityContract => throw null; } record G : A { protected sealed override System.Type EqualityContract => throw null; } sealed record H : A { protected sealed override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (7,27): error CS8876: 'B.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("B.EqualityContract", "A").WithLocation(7, 27), // (7,27): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(7, 27), // (7,27): warning CS0114: 'B.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 27), // (13,27): warning CS0628: 'C.EqualityContract': new protected member declared in sealed type // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("C.EqualityContract").WithLocation(13, 27), // (13,27): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(13, 27), // (13,27): warning CS0114: 'C.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract").WithLocation(13, 27), // (14,12): warning CS0628: 'C.EqualityContract.get': new protected member declared in sealed type // => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("C.EqualityContract.get").WithLocation(14, 12), // (19,35): warning CS0628: 'D.EqualityContract': new protected member declared in sealed type // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("D.EqualityContract").WithLocation(19, 35), // (19,35): error CS8876: 'D.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "A").WithLocation(19, 35), // (19,35): warning CS0114: 'D.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("D.EqualityContract", "A.EqualityContract").WithLocation(19, 35), // (20,12): error CS0549: 'D.EqualityContract.get' is a new virtual member in sealed type 'D' // => throw null; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "throw null").WithArguments("D.EqualityContract.get", "D").WithLocation(20, 12), // (25,35): error CS8876: 'E.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("E.EqualityContract", "A").WithLocation(25, 35), // (25,35): warning CS0114: 'E.EqualityContract' hides inherited member 'A.EqualityContract'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "EqualityContract").WithArguments("E.EqualityContract", "A.EqualityContract").WithLocation(25, 35), // (37,43): error CS8872: 'G.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("G.EqualityContract").WithLocation(37, 43) ); } [Fact] public void EqualityContract_14() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_15() { var source = @" record A { protected virtual int EqualityContract => throw null; } record B : A { } record C : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.VerifyEmitDiagnostics( // (4,27): error CS8874: Record member 'A.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("A.EqualityContract", "System.Type").WithLocation(4, 27), // (8,8): error CS1715: 'B.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // record B : A Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "B").WithArguments("B.EqualityContract", "A.EqualityContract", "int").WithLocation(8, 8), // (14,36): error CS1715: 'C.EqualityContract': type must be 'int' to match overridden member 'A.EqualityContract' // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "EqualityContract").WithArguments("C.EqualityContract", "A.EqualityContract", "int").WithLocation(14, 36) ); } [Fact] public void EqualityContract_16() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot final virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { new protected virtual System.Type EqualityContract => throw null; } public record D : A { new protected virtual int EqualityContract => throw null; } public record E : A { new protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // public record B : A { Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(2, 15), // (6,39): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 39), // (11,31): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS0506: 'F.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "EqualityContract").WithArguments("F.EqualityContract", "A.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_17() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class A "; var source = @" public record B : A { } public record C : A { protected virtual System.Type EqualityContract => throw null; } public record D : A { protected virtual int EqualityContract => throw null; } public record E : A { protected virtual Type EqualityContract => throw null; } public record F : A { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS0115: 'B.EqualityContract': no suitable method found to override // public record B : A { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B.EqualityContract").WithLocation(2, 15), // (6,35): error CS8876: 'C.EqualityContract' does not override expected property from 'A'. // protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("C.EqualityContract", "A").WithLocation(6, 35), // (11,27): error CS8874: Record member 'D.EqualityContract' must return 'Type'. // protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("D.EqualityContract", "System.Type").WithLocation(11, 27), // (16,23): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 23), // (21,36): error CS0115: 'F.EqualityContract': no suitable method found to override // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_OverrideNotExpected, "EqualityContract").WithArguments("F.EqualityContract").WithLocation(21, 36) ); } [Fact] public void EqualityContract_18() { var ilSource = @" .class public auto ansi beforefieldinit A extends System.Object { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public newslot virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance class [mscorlib]System.Type get_EqualityContract () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::get_EqualityContract .property instance class [mscorlib]System.Type EqualityContract() { .get instance class [mscorlib]System.Type A::get_EqualityContract() } } // end of class A .class public auto ansi beforefieldinit B extends A { // Methods .method public hidebysig specialname newslot virtual instance class A '" + WellKnownMemberNames.CloneMethodName + @"' () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::'" + WellKnownMemberNames.CloneMethodName + @"' .method public hidebysig virtual instance bool Equals ( object other ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public hidebysig virtual instance int32 GetHashCode () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::GetHashCode .method public final virtual instance bool Equals ( class A '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::Equals .method public newslot virtual instance bool Equals ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::Equals .method family hidebysig specialname rtspecialname instance void .ctor ( class B '' ) cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method B::.ctor .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { .maxstack 8 IL_0000: ldnull IL_0001: throw } // end of method A::.ctor .method family hidebysig newslot virtual instance bool '" + WellKnownMemberNames.PrintMembersMethodName + @"' (class [mscorlib]System.Text.StringBuilder builder) cil managed { IL_0000: ldnull IL_0001: throw } } // end of class B "; var source = @" public record C : B { } public record D : B { new protected virtual System.Type EqualityContract => throw null; } public record E : B { new protected virtual int EqualityContract => throw null; } public record F : B { new protected virtual Type EqualityContract => throw null; } public record G : B { protected override System.Type EqualityContract => throw null; } "; var comp = CreateCompilationWithIL(new[] { source, IsExternalInitTypeDefinition }, ilSource: ilSource, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (2,15): error CS8876: 'C.EqualityContract' does not override expected property from 'B'. // public record C : B { Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "C").WithArguments("C.EqualityContract", "B").WithLocation(2, 15), // (6,39): error CS8876: 'D.EqualityContract' does not override expected property from 'B'. // new protected virtual System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("D.EqualityContract", "B").WithLocation(6, 39), // (11,31): error CS8874: Record member 'E.EqualityContract' must return 'Type'. // new protected virtual int EqualityContract Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "EqualityContract").WithArguments("E.EqualityContract", "System.Type").WithLocation(11, 31), // (16,27): error CS0246: The type or namespace name 'Type' could not be found (are you missing a using directive or an assembly reference?) // new protected virtual Type EqualityContract Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Type").WithArguments("Type").WithLocation(16, 27), // (21,36): error CS8876: 'G.EqualityContract' does not override expected property from 'B'. // protected override System.Type EqualityContract Diagnostic(ErrorCode.ERR_DoesNotOverrideBaseEqualityContract, "EqualityContract").WithArguments("G.EqualityContract", "B").WithLocation(21, 36) ); } [Fact] public void EqualityContract_19() { var source = @"sealed record A { protected static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,34): warning CS0628: 'A.EqualityContract': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8879: Record member 'A.EqualityContract' must be private. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NonPrivateAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,34): error CS8877: Record member 'A.EqualityContract' may not be static. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 34), // (3,54): warning CS0628: 'A.EqualityContract.get': new protected member declared in sealed type // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "throw null").WithArguments("A.EqualityContract.get").WithLocation(3, 54) ); } [Fact] public void EqualityContract_20() { var source = @"sealed record A { private static System.Type EqualityContract => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (3,32): error CS8877: Record member 'A.EqualityContract' may not be static. // private static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_StaticAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 32) ); } [Fact] public void EqualityContract_21() { var source = @" sealed record A { static void Main() { A a1 = new A(); A a2 = new A(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("A.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type A.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Private, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.False(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_22() { var source = @" record A; sealed record B : A { static void Main() { A a1 = new B(); A a2 = new B(); System.Console.WriteLine(a1.Equals(a2)); } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "True").VerifyDiagnostics(); var equalityContract = comp.GetMembers("B.EqualityContract").OfType<SynthesizedRecordEqualityContractProperty>().Single(); Assert.Equal("System.Type B.EqualityContract { get; }", equalityContract.ToTestDisplayString()); Assert.Equal(Accessibility.Protected, equalityContract.DeclaredAccessibility); Assert.False(equalityContract.IsAbstract); Assert.False(equalityContract.IsVirtual); Assert.True(equalityContract.IsOverride); Assert.False(equalityContract.IsSealed); Assert.True(equalityContract.IsImplicitlyDeclared); Assert.Empty(equalityContract.DeclaringSyntaxReferences); } [Fact] public void EqualityContract_23() { var source = @" record A { protected static System.Type EqualityContract => throw null; } record B : A; "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,34): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected static System.Type EqualityContract => throw null; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(4, 34), // (7,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(7, 8) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_SetterOnlyProperty() { var src = @" record R { protected virtual System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,35): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected virtual System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(4, 35) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_24_GetterAndSetterProperty() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R; "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN"); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_25_SetterOnlyProperty_DerivedRecord() { var src = @" record Base; record R : Base { protected override System.Type EqualityContract { set { } } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (5,36): error CS8906: Record equality contract property 'R.EqualityContract' must have a get accessor. // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_EqualityContractRequiresGetter, "EqualityContract").WithArguments("R.EqualityContract").WithLocation(5, 36), // (5,55): error CS0546: 'R.EqualityContract.set': cannot override because 'Base.EqualityContract' does not have an overridable set accessor // protected override System.Type EqualityContract { set { } } Diagnostic(ErrorCode.ERR_NoSetToOverride, "set").WithArguments("R.EqualityContract.set", "Base.EqualityContract").WithLocation(5, 55) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_26_SetterOnlyProperty_InMetadata() { // `record Base;` with modified EqualityContract property, method bodies simplified and nullability removed var il = @" .class public auto ansi beforefieldinit Base extends [mscorlib]System.Object implements class [mscorlib]System.IEquatable`1<class Base> { .method public hidebysig virtual instance string ToString () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig newslot virtual instance bool PrintMembers( class [mscorlib] System.Text.StringBuilder builder ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Inequality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname static bool op_Equality( class Base r1, class Base r2 ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance int32 GetHashCode () cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig virtual instance bool Equals( object obj ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance bool Equals( class Base other ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig newslot virtual instance class Base '<Clone>$'() cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname rtspecialname instance void .ctor ( class Base original ) cil managed { IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } .method family hidebysig specialname newslot virtual instance void set_EqualityContract ( class [mscorlib]System.Type 'value' ) cil managed { IL_0000: ldnull IL_0001: throw } // Property has a setter but no getter .property instance class [mscorlib]System.Type EqualityContract() { .set instance void Base::set_EqualityContract(class [mscorlib]System.Type) } } "; var src = @" record R : Base; "; var comp = CreateCompilationWithIL(src, il); comp.VerifyEmitDiagnostics( // (2,8): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // record R : Base; Diagnostic(ErrorCode.ERR_NoGetToOverride, "R").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(2, 8) ); var src2 = @" record R : Base { protected override System.Type EqualityContract => typeof(R); } "; var comp2 = CreateCompilationWithIL(src2, il); comp2.VerifyEmitDiagnostics( // (4,56): error CS0545: 'R.EqualityContract.get': cannot override because 'Base.EqualityContract' does not have an overridable get accessor // protected override System.Type EqualityContract => typeof(R); Diagnostic(ErrorCode.ERR_NoGetToOverride, "typeof(R)").WithArguments("R.EqualityContract.get", "Base.EqualityContract").WithLocation(4, 56) ); } [Fact] [WorkItem(48723, "https://github.com/dotnet/roslyn/issues/48723")] public void EqualityContract_27_GetterAndSetterProperty_ExplicitlyOverridden() { var src = @" _ = new R() == new R2(); record R { protected virtual System.Type EqualityContract { get { System.Console.Write(""RAN ""); return GetType(); } set { } } } record R2 : R { protected override System.Type EqualityContract { get { System.Console.Write(""RAN2 ""); return GetType(); } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "RAN RAN2"); } [Fact] public void EqualityOperators_01() { var source = @" record A(int X) { public virtual bool Equals(ref A other) => throw null; static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); Test(new A(4), new B(4, 5)); Test(new B(6, 7), new B(6, 7)); Test(new B(8, 9), new B(8, 10)); var a = new A(11); Test(a, a); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } record B(int X, int Y) : A(X); "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False False False True True True True False False False False True True False False True True True True False False False False True True True True False False ").VerifyDiagnostics(); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_02() { var source = @" record B; record A(int X) : B { public virtual bool Equals(A other) { System.Console.WriteLine(""Equals(A other)""); return base.Equals(other) && X == other.X; } static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); var a = new A(11); Test(a, a); Test(new A(3), new B()); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } static void Test(A a1, B b2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == b2, b2 == a1, a1 != b2, b2 != a1); } } "; var verifier = CompileAndVerify(source, expectedOutput: @" True True False False Equals(A other) Equals(A other) False False True True Equals(A other) Equals(A other) Equals(A other) Equals(A other) True True False False Equals(A other) Equals(A other) Equals(A other) Equals(A other) False False True True True True False False Equals(A other) Equals(A other) False False True True ").VerifyDiagnostics( // (6,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(6, 25) ); var comp = (CSharpCompilation)verifier.Compilation; MethodSymbol op = comp.GetMembers("A." + WellKnownMemberNames.EqualityOperatorName).OfType<SynthesizedRecordEqualityOperator>().Single(); Assert.Equal("System.Boolean A.op_Equality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); op = comp.GetMembers("A." + WellKnownMemberNames.InequalityOperatorName).OfType<SynthesizedRecordInequalityOperator>().Single(); Assert.Equal("System.Boolean A.op_Inequality(A? left, A? right)", op.ToTestDisplayString()); Assert.Equal(Accessibility.Public, op.DeclaredAccessibility); Assert.True(op.IsStatic); Assert.False(op.IsAbstract); Assert.False(op.IsVirtual); Assert.False(op.IsOverride); Assert.False(op.IsSealed); Assert.True(op.IsImplicitlyDeclared); verifier.VerifyIL("bool A.op_Equality(A, A)", @" { // Code size 19 (0x13) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0011 IL_0004: ldarg.0 IL_0005: brfalse.s IL_000f IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: callvirt ""bool A.Equals(A)"" IL_000e: ret IL_000f: ldc.i4.0 IL_0010: ret IL_0011: ldc.i4.1 IL_0012: ret } "); verifier.VerifyIL("bool A.op_Inequality(A, A)", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: call ""bool A.op_Equality(A, A)"" IL_0007: ldc.i4.0 IL_0008: ceq IL_000a: ret } "); } [Fact] public void EqualityOperators_03() { var source = @" record A { public static bool operator==(A r1, A r2) => throw null; public static bool operator==(A r1, string r2) => throw null; public static bool operator!=(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool operator==(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "==").WithArguments("op_Equality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_04() { var source = @" record A { public static bool operator!=(A r1, A r2) => throw null; public static bool operator!=(string r1, A r2) => throw null; public static bool operator==(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,32): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool operator!=(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "!=").WithArguments("op_Inequality", "A").WithLocation(4, 32) ); } [Fact] public void EqualityOperators_05() { var source = @" record A { public static bool op_Equality(A r1, A r2) => throw null; public static bool op_Equality(string r1, A r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Equality' with the same parameter types // public static bool op_Equality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Equality").WithArguments("op_Equality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_06() { var source = @" record A { public static bool op_Inequality(A r1, A r2) => throw null; public static bool op_Inequality(A r1, string r2) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (4,24): error CS0111: Type 'A' already defines a member called 'op_Inequality' with the same parameter types // public static bool op_Inequality(A r1, A r2) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "op_Inequality").WithArguments("op_Inequality", "A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_07() { var source = @" record A { public static bool Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0736: 'A' does not implement instance interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement the interface member because it is static. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(2, 8), // (4,24): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public static bool Equals(A other) Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(4, 24), // (4,24): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public static bool Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 24) ); } [Fact] public void EqualityOperators_08() { var source = @" record A { public virtual string Equals(A other) => throw null; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,8): error CS0738: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement 'IEquatable<A>.Equals(A)' because it does not have the matching return type of 'bool'. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)", "bool").WithLocation(2, 8), // (4,27): error CS8874: Record member 'A.Equals(A)' must return 'bool'. // public virtual string Equals(A other) Diagnostic(ErrorCode.ERR_SignatureMismatchInRecord, "Equals").WithArguments("A.Equals(A)", "bool").WithLocation(4, 27), // (4,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual string Equals(A other) Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(4, 27) ); } [Theory] [CombinatorialData] public void EqualityOperators_09(bool useImageReference) { var source1 = @" public record A(int X) { } "; var comp1 = CreateCompilation(source1); var source2 = @" class Program { static void Main() { Test(null, null); Test(null, new A(0)); Test(new A(1), new A(1)); Test(new A(2), new A(3)); } static void Test(A a1, A a2) { System.Console.WriteLine(""{0} {1} {2} {3}"", a1 == a2, a2 == a1, a1 != a2, a2 != a1); } } "; CompileAndVerify(source2, references: new[] { useImageReference ? comp1.EmitToImageReference() : comp1.ToMetadataReference() }, expectedOutput: @" True True False False False False True True True True False False False False True True ").VerifyDiagnostics(); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_01() { var src = @"record C(object Q) { public object P { get; } public object P { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'C' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.Q { get; init; }", "System.Object C.P { get; }", "System.Object C.P { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [WorkItem(44692, "https://github.com/dotnet/roslyn/issues/44692")] [Fact] public void DuplicateProperty_02() { var src = @"record C(object P, object Q) { public object P { get; } public int P { get; } public int Q { get; } public object Q { get; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (1,17): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(1, 17), // (1,27): error CS8866: Record member 'C.Q' must be a readable instance property or field of type 'object' to match positional parameter 'Q'. // record C(object P, object Q) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "Q").WithArguments("C.Q", "object", "Q").WithLocation(1, 27), // (1,27): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record C(object P, object Q) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(1, 27), // (4,16): error CS0102: The type 'C' already contains a definition for 'P' // public int P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 16), // (6,19): error CS0102: The type 'C' already contains a definition for 'Q' // public object Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 19)); var actualMembers = GetProperties(comp, "C").ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type C.EqualityContract { get; }", "System.Object C.P { get; }", "System.Int32 C.P { get; }", "System.Int32 C.Q { get; }", "System.Object C.Q { get; }", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void DuplicateProperty_03() { var src = @"record A { public object P { get; } public object P { get; } public object Q { get; } public int Q { get; } } record B(object Q) : A { }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0102: The type 'A' already contains a definition for 'P' // public object P { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("A", "P").WithLocation(4, 19), // (6,16): error CS0102: The type 'A' already contains a definition for 'Q' // public int Q { get; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("A", "Q").WithLocation(6, 16), // (8,17): warning CS8907: Parameter 'Q' is unread. Did you forget to use it to initialize the property with that name? // record B(object Q) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Q").WithArguments("Q").WithLocation(8, 17)); var actualMembers = GetProperties(comp, "B").ToTestDisplayStrings(); AssertEx.Equal(new[] { "System.Type B.EqualityContract { get; }" }, actualMembers); } [Fact] public void NominalRecordWith() { var src = @" using System; record C { public int X { get; init; } public string Y; public int Z { get; set; } public static void Main() { var c = new C() { X = 1, Y = ""2"", Z = 3 }; var c2 = new C() { X = 1, Y = ""2"", Z = 3 }; Console.WriteLine(c.Equals(c2)); var c3 = c2 with { X = 3, Y = ""2"", Z = 1 }; Console.WriteLine(c.Equals(c2)); Console.WriteLine(c3.Equals(c2)); Console.WriteLine(c2.X + "" "" + c2.Y + "" "" + c2.Z); } }"; CompileAndVerify(src, expectedOutput: @" True True False 1 2 3").VerifyDiagnostics(); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = c with { X = 2 }; Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = d with { X = 2, Y = 3 }; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); C c3 = d; C c4 = d2; c3 = c3 with { X = 3 }; c4 = c4 with { X = 4 }; d = (D)c3; d2 = (D)c4; Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } }"; var verifier = CompileAndVerify(src2, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3 3 2 4 3").VerifyDiagnostics(); verifier.VerifyIL("E.Main", @" { // Code size 318 (0x13e) .maxstack 3 .locals init (C V_0, //c D V_1, //d D V_2, //d2 C V_3, //c3 C V_4, //c4 int V_5) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.1 IL_0007: callvirt ""void C.X.init"" IL_000c: stloc.0 IL_000d: ldloc.0 IL_000e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0013: dup IL_0014: ldc.i4.2 IL_0015: callvirt ""void C.X.init"" IL_001a: ldloc.0 IL_001b: callvirt ""int C.X.get"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: callvirt ""int C.X.get"" IL_002a: call ""void System.Console.WriteLine(int)"" IL_002f: ldc.i4.2 IL_0030: newobj ""D..ctor(int)"" IL_0035: dup IL_0036: ldc.i4.1 IL_0037: callvirt ""void C.X.init"" IL_003c: stloc.1 IL_003d: ldloc.1 IL_003e: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_0043: castclass ""D"" IL_0048: dup IL_0049: ldc.i4.2 IL_004a: callvirt ""void C.X.init"" IL_004f: dup IL_0050: ldc.i4.3 IL_0051: callvirt ""void D.Y.init"" IL_0056: stloc.2 IL_0057: ldloc.1 IL_0058: callvirt ""int C.X.get"" IL_005d: stloc.s V_5 IL_005f: ldloca.s V_5 IL_0061: call ""string int.ToString()"" IL_0066: ldstr "" "" IL_006b: ldloc.1 IL_006c: callvirt ""int D.Y.get"" IL_0071: stloc.s V_5 IL_0073: ldloca.s V_5 IL_0075: call ""string int.ToString()"" IL_007a: call ""string string.Concat(string, string, string)"" IL_007f: call ""void System.Console.WriteLine(string)"" IL_0084: ldloc.2 IL_0085: callvirt ""int C.X.get"" IL_008a: stloc.s V_5 IL_008c: ldloca.s V_5 IL_008e: call ""string int.ToString()"" IL_0093: ldstr "" "" IL_0098: ldloc.2 IL_0099: callvirt ""int D.Y.get"" IL_009e: stloc.s V_5 IL_00a0: ldloca.s V_5 IL_00a2: call ""string int.ToString()"" IL_00a7: call ""string string.Concat(string, string, string)"" IL_00ac: call ""void System.Console.WriteLine(string)"" IL_00b1: ldloc.1 IL_00b2: stloc.3 IL_00b3: ldloc.2 IL_00b4: stloc.s V_4 IL_00b6: ldloc.3 IL_00b7: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00bc: dup IL_00bd: ldc.i4.3 IL_00be: callvirt ""void C.X.init"" IL_00c3: stloc.3 IL_00c4: ldloc.s V_4 IL_00c6: callvirt ""C C." + WellKnownMemberNames.CloneMethodName + @"()"" IL_00cb: dup IL_00cc: ldc.i4.4 IL_00cd: callvirt ""void C.X.init"" IL_00d2: stloc.s V_4 IL_00d4: ldloc.3 IL_00d5: castclass ""D"" IL_00da: stloc.1 IL_00db: ldloc.s V_4 IL_00dd: castclass ""D"" IL_00e2: stloc.2 IL_00e3: ldloc.1 IL_00e4: callvirt ""int C.X.get"" IL_00e9: stloc.s V_5 IL_00eb: ldloca.s V_5 IL_00ed: call ""string int.ToString()"" IL_00f2: ldstr "" "" IL_00f7: ldloc.1 IL_00f8: callvirt ""int D.Y.get"" IL_00fd: stloc.s V_5 IL_00ff: ldloca.s V_5 IL_0101: call ""string int.ToString()"" IL_0106: call ""string string.Concat(string, string, string)"" IL_010b: call ""void System.Console.WriteLine(string)"" IL_0110: ldloc.2 IL_0111: callvirt ""int C.X.get"" IL_0116: stloc.s V_5 IL_0118: ldloca.s V_5 IL_011a: call ""string int.ToString()"" IL_011f: ldstr "" "" IL_0124: ldloc.2 IL_0125: callvirt ""int D.Y.get"" IL_012a: stloc.s V_5 IL_012c: ldloca.s V_5 IL_012e: call ""string int.ToString()"" IL_0133: call ""string string.Concat(string, string, string)"" IL_0138: call ""void System.Console.WriteLine(string)"" IL_013d: ret }"); } [Theory] [InlineData(true)] [InlineData(false)] public void WithExprReference_WithCovariantReturns(bool emitRef) { var src = @" public record C { public int X { get; init; } } public record D(int Y) : C;"; var comp = CreateCompilation(RuntimeUtilities.IsCoreClrRuntime ? src : new[] { src, IsExternalInitTypeDefinition }, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics(); var src2 = @" using System; class E { public static void Main() { var c = new C() { X = 1 }; var c2 = CHelper(c); Console.WriteLine(c.X); Console.WriteLine(c2.X); var d = new D(2) { X = 1 }; var d2 = DHelper(d); Console.WriteLine(d.X + "" "" + d.Y); Console.WriteLine(d2.X + "" "" + d2.Y); } private static C CHelper(C c) { return c with { X = 2 }; } private static D DHelper(D d) { return d with { X = 2, Y = 3 }; } }"; var verifier = CompileAndVerify(RuntimeUtilities.IsCoreClrRuntime ? src2 : new[] { src2, IsExternalInitTypeDefinition }, references: new[] { emitRef ? comp.EmitToImageReference() : comp.ToMetadataReference() }, expectedOutput: @" 1 2 1 2 2 3", targetFramework: TargetFramework.StandardLatest).VerifyDiagnostics().VerifyIL("E.CHelper", @" { // Code size 14 (0xe) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: ret } "); if (RuntimeUtilities.IsCoreClrRuntime) { verifier.VerifyIL("E.DHelper", @" { // Code size 21 (0x15) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""D D.<Clone>$()"" IL_0006: dup IL_0007: ldc.i4.2 IL_0008: callvirt ""void C.X.init"" IL_000d: dup IL_000e: ldc.i4.3 IL_000f: callvirt ""void D.Y.init"" IL_0014: ret } "); } else { verifier.VerifyIL("E.DHelper", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldarg.0 IL_0001: callvirt ""C C.<Clone>$()"" IL_0006: castclass ""D"" IL_000b: dup IL_000c: ldc.i4.2 IL_000d: callvirt ""void C.X.init"" IL_0012: dup IL_0013: ldc.i4.3 IL_0014: callvirt ""void D.Y.init"" IL_0019: ret } "); } } private static ImmutableArray<Symbol> GetProperties(CSharpCompilation comp, string typeName) { return comp.GetMember<NamedTypeSymbol>(typeName).GetMembers().WhereAsArray(m => m.Kind == SymbolKind.Property); } [Fact] public void BaseArguments_01() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X, int Y = 123) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } C(int X, int Y, int Z = 124) : this(X, Y) {} }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal(Accessibility.Public, symbol.ContainingSymbol.DeclaredAccessibility); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(X, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Equal("Base..ctor(System.Int32 X, System.Int32 Y)", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); #nullable disable var operation = model.GetOperation(baseWithargs); VerifyOperationTree(comp, operation, @" IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); Assert.Null(model.GetOperation(baseWithargs.Type)); Assert.Null(model.GetOperation(baseWithargs.Parent)); Assert.Same(operation.Parent.Parent, model.GetOperation(baseWithargs.Parent.Parent)); Assert.Equal(SyntaxKind.RecordDeclaration, baseWithargs.Parent.Parent.Kind()); VerifyOperationTree(comp, operation.Parent.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'record C(in ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'record C(in ... }') ExpressionBody: null "); Assert.Null(operation.Parent.Parent.Parent); VerifyFlowGraph(comp, operation.Parent.Parent.Syntax, @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().First(); Assert.Equal("= 123", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Y = 123]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 123') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 123) (Syntax: '123') "); #nullable enable } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y)", baseWithargs.ToString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo((SyntaxNode)baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", model.GetSymbolInfo(baseWithargs).Symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, [System.Int32 Y = 123])", CSharpExtensions.GetSymbolInfo(model, baseWithargs).Symbol.ToTestDisplayString()); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); model.VerifyOperationTree(baseWithargs, @" IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); var equalsValue = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().Last(); Assert.Equal("= 124", equalsValue.ToString()); model.VerifyOperationTree(equalsValue, @" IParameterInitializerOperation (Parameter: [System.Int32 Z = 124]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 124') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 124) (Syntax: '124') "); model.VerifyOperationTree(baseWithargs.Parent, @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'C(int X, in ... is(X, Y) {}') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: ': this(X, Y)') Expression: IInvocationOperation ( C..ctor(System.Int32 X, [System.Int32 Y = 123])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': this(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: ': this(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{}') ExpressionBody: null "); } } [Fact] public void BaseArguments_02() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { public static void Main() { var c = new C(1); } private static int Test(int x, out int y) { y = 2; return x; } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var yDecl = OutVarTests.GetOutVarDeclaration(tree, "y"); var yRef = OutVarTests.GetReferences(tree, "y").ToArray(); Assert.Equal(2, yRef.Length); OutVarTests.VerifyModelForOutVar(model, yDecl, yRef[0]); OutVarTests.VerifyNotAnOutLocal(model, yRef[1]); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Test(X, out var y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var y = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "y").First(); Assert.Equal("y", y.Parent!.ToString()); Assert.Equal("(Test(X, out var y), y)", y.Parent!.Parent!.ToString()); Assert.Equal("Base(Test(X, out var y), y)", y.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(y).Symbol; Assert.Equal(SymbolKind.Local, symbol!.Kind); Assert.Equal("System.Int32 y", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "y")); Assert.Contains("y", model.LookupNames(x.SpanStart)); var test = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "Test").First(); Assert.Equal("(Test(X, out var y), y)", test.Parent!.Parent!.Parent!.ToString()); symbol = model.GetSymbolInfo(test).Symbol; Assert.Equal(SymbolKind.Method, symbol!.Kind); Assert.Equal("System.Int32 C.Test(System.Int32 x, out System.Int32 y)", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "Test")); Assert.Contains("Test", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_03() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,16): error CS8861: Unexpected argument list. // record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_04() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_05() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24), // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); foreach (var x in xs) { Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_06() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C(int X, int Y) : Base(X, Y) { } partial record C : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (17,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(17, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[0], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[1])); } [Fact] public void BaseArguments_07() { var src = @" using System; record Base { public Base(int X, int Y) { } public Base() {} } partial record C : Base(X, Y) { } partial record C(int X, int Y) : Base(X, Y) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (13,24): error CS8861: Unexpected argument list. // partial record C : Base(X, Y) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X, Y)").WithLocation(13, 24) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var xs = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ToArray(); Assert.Equal(2, xs.Length); var x = xs[1]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); x = xs[0]; Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); var recordDeclarations = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Skip(1).ToArray(); Assert.Equal("C", recordDeclarations[0].Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclarations[0])); Assert.Equal("C", recordDeclarations[1].Identifier.ValueText); model.VerifyOperationTree(recordDeclarations[1], @" IConstructorBodyOperation (OperationKind.ConstructorBody, Type: null) (Syntax: 'partial rec ... }') Initializer: IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsImplicit) (Syntax: 'Base(X, Y)') Expression: IInvocationOperation ( Base..ctor(System.Int32 X, System.Int32 Y)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'Base(X, Y)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Base, IsImplicit) (Syntax: 'Base(X, Y)') Arguments(2): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: 'X') IParameterReferenceOperation: X (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'X') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: Y) (OperationKind.Argument, Type: null) (Syntax: 'Y') IParameterReferenceOperation: Y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'Y') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) BlockBody: IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'partial rec ... }') ExpressionBody: null "); } [Fact] public void BaseArguments_08() { var src = @" record Base { public Base(int Y) { } public Base() {} } record C(int X) : Base(Y) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0120: An object reference is required for the non-static field, method, or property 'C.Y' // record C(int X) : Base(Y) Diagnostic(ErrorCode.ERR_ObjectRequired, "Y").WithArguments("C.Y").WithLocation(11, 24) ); } [Fact] public void BaseArguments_09() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X) : Base(this.X) { public int Y = 0; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,24): error CS0027: Keyword 'this' is not available in the current context // record C(int X) : Base(this.X) Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(11, 24) ); } [Fact] public void BaseArguments_10() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(dynamic X) : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,27): error CS1975: The constructor call needs to be dynamically dispatched, but cannot be because it is part of a constructor initializer. Consider casting the dynamic arguments. // record C(dynamic X) : Base(X) Diagnostic(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor, "(X)").WithLocation(11, 27) ); } [Fact] public void BaseArguments_11() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X) : Base(Test(X, out var y), y) { int Z = y; private static int Test(int x, out int y) { y = 2; return x; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): error CS0103: The name 'y' does not exist in the current context // int Z = y; Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(13, 13) ); } [Fact] public void BaseArguments_12() { var src = @" using System; class Base { public Base(int X) { } } class C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,7): error CS7036: There is no argument given that corresponds to the required formal parameter 'X' of 'Base.Base(int)' // class C : Base(X) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("X", "Base.Base(int)").WithLocation(11, 7), // (11,15): error CS8861: Unexpected argument list. // class C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(11, 15) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_13() { var src = @" using System; interface Base { } struct C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,16): error CS8861: Unexpected argument list. // struct C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 16) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_14() { var src = @" using System; interface Base { } interface C : Base(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,19): error CS8861: Unexpected argument list. // interface C : Base(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(8, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("Base(X)", x.Parent!.Parent!.Parent!.ToString()); var symbolInfo = model.GetSymbolInfo(x); Assert.Null(symbolInfo.Symbol); Assert.Empty(symbolInfo.CandidateSymbols); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); Assert.Same("<global namespace>", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Empty(model.LookupSymbols(x.SpanStart, name: "X")); Assert.DoesNotContain("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_15() { var src = @" using System; record Base { public Base(int X, int Y) { Console.WriteLine(X); Console.WriteLine(Y); } public Base() {} } partial record C { } partial record C(int X, int Y) : Base(X, Y) { int Z = 123; public static void Main() { var c = new C(1, 2); Console.WriteLine(c.Z); } } partial record C { } "; var verifier = CompileAndVerify(src, expectedOutput: @" 1 2 123").VerifyDiagnostics(); verifier.VerifyIL("C..ctor(int, int)", @" { // Code size 31 (0x1f) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int C.<X>k__BackingField"" IL_0007: ldarg.0 IL_0008: ldarg.2 IL_0009: stfld ""int C.<Y>k__BackingField"" IL_000e: ldarg.0 IL_000f: ldc.i4.s 123 IL_0011: stfld ""int C.Z"" IL_0016: ldarg.0 IL_0017: ldarg.1 IL_0018: ldarg.2 IL_0019: call ""Base..ctor(int, int)"" IL_001e: ret } "); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").ElementAt(1); Assert.Equal("Base(X, Y)", x.Parent!.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X, System.Int32 Y)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Same(symbol.ContainingSymbol, model.GetEnclosingSymbol(x.SpanStart)); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void BaseArguments_16() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => X) { public static void Main() { var c = new C(1); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"1").VerifyDiagnostics(); } [Fact] public void BaseArguments_17() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X, out var y), Test(X, out var z)) { int Z = z; private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,28): 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 // : Base(Test(X, out var y), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(12, 28), // (15,13): error CS0103: The name 'z' does not exist in the current context // int Z = z; Diagnostic(ErrorCode.ERR_NameNotInContext, "z").WithArguments("z").WithLocation(15, 13) ); } [Fact] public void BaseArguments_18() { var src = @" record Base { public Base(int X, int Y) { } public Base() {} } record C(int X, int y) : Base(Test(X + 1, out var z), Test(X + 2, out var z)) { private static int Test(int x, out int y) { y = 2; return x; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,32): error CS0128: A local variable or function named 'z' is already defined in this scope // Test(X + 2, out var z)) Diagnostic(ErrorCode.ERR_LocalDuplicate, "z").WithArguments("z").WithLocation(13, 32) ); } [Fact] public void BaseArguments_19() { var src = @" record Base { public Base(int X) { } public Base() {} } record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : this(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,30): error CS1729: 'Base' does not contain a constructor that takes 2 arguments // record C(int X, int Y) : Base(GetInt(X, out var xx) + xx, Y) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(GetInt(X, out var xx) + xx, Y)").WithArguments("Base", "2").WithLocation(11, 30), // (13,30): error CS1729: 'C' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : this(X, Y, Z, 1) {} Diagnostic(ErrorCode.ERR_BadCtorArgCount, "this").WithArguments("C", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(Base original)", "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); model = comp.GetSemanticModel(tree); Assert.Empty(model.GetMemberGroup(baseWithargs)); model = comp.GetSemanticModel(tree); SemanticModel speculativeModel; speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.True(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out speculativeModel!)); var xxDecl = OutVarTests.GetOutVarDeclaration(speculativePrimaryInitializer.SyntaxTree, "xx"); var xxRef = OutVarTests.GetReferences(speculativePrimaryInitializer.SyntaxTree, "xx").ToArray(); Assert.Equal(1, xxRef.Length); OutVarTests.VerifyModelForOutVar(speculativeModel, xxDecl, xxRef); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel!.GetSymbolInfo((SyntaxNode)speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", speculativeModel.GetSymbolInfo(speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Equal("Base..ctor(System.Int32 X)", CSharpExtensions.GetSymbolInfo(speculativeModel, speculativePrimaryInitializer).Symbol.ToTestDisplayString()); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": this(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "C..ctor(System.Int32 X, System.Int32 Y)", "C..ctor(C original)", "C..ctor(System.Int32 X, System.Int32 Y, System.Int32 Z)" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void BaseArguments_20() { var src = @" class Base { public Base(int X) { } public Base() {} } class C : Base(GetInt(X, out var xx) + xx, Y), I { C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } static int GetInt(int x1, out int x2) { throw null; } } interface I {} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,15): error CS8861: Unexpected argument list. // class C : Base(GetInt(X, out var xx) + xx, Y), I Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(GetInt(X, out var xx) + xx, Y)").WithLocation(11, 15), // (13,30): error CS1729: 'Base' does not contain a constructor that takes 4 arguments // C(int X, int Y, int Z) : base(X, Y, Z, 1) { return; } Diagnostic(ErrorCode.ERR_BadCtorArgCount, "base").WithArguments("Base", "4").WithLocation(13, 30) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); SymbolInfo symbolInfo; PrimaryConstructorBaseTypeSyntax speculativePrimaryInitializer; ConstructorInitializerSyntax speculativeBaseInitializer; { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<PrimaryConstructorBaseTypeSyntax>().Single(); Assert.Equal("Base(GetInt(X, out var xx) + xx, Y)", baseWithargs.ToString()); Assert.Equal("Base", model.GetTypeInfo(baseWithargs.Type).Type.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetTypeInfo(baseWithargs)); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs)); Assert.Empty(model.GetMemberGroup(baseWithargs)); speculativePrimaryInitializer = baseWithargs.WithArgumentList(baseWithargs.ArgumentList.WithArguments(baseWithargs.ArgumentList.Arguments.RemoveAt(1))); speculativeBaseInitializer = SyntaxFactory.ConstructorInitializer(SyntaxKind.BaseConstructorInitializer, speculativePrimaryInitializer.ArgumentList); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.False(model.TryGetSpeculativeSemanticModel(tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Single().SpanStart, speculativeBaseInitializer, out _)); var otherBasePosition = ((BaseListSyntax)baseWithargs.Parent!).Types[1].SpanStart; Assert.False(model.TryGetSpeculativeSemanticModel(otherBasePosition, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.SpanStart, speculativePrimaryInitializer, out _)); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); Assert.Throws<ArgumentNullException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (PrimaryConstructorBaseTypeSyntax)null!, out _)); Assert.Throws<ArgumentException>(() => model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, baseWithargs, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(otherBasePosition, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, otherBasePosition, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single().ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } { var baseWithargs = tree.GetRoot().DescendantNodes().OfType<ConstructorInitializerSyntax>().Single(); Assert.Equal(": base(X, Y, Z, 1)", baseWithargs.ToString()); symbolInfo = model.GetSymbolInfo((SyntaxNode)baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); string[] candidates = new[] { "Base..ctor(System.Int32 X)", "Base..ctor()" }; Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = model.GetSymbolInfo(baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); symbolInfo = CSharpExtensions.GetSymbolInfo(model, baseWithargs); Assert.Null(symbolInfo.Symbol); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); Assert.Equal(candidates, symbolInfo.CandidateSymbols.Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup((SyntaxNode)baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(model.GetMemberGroup(baseWithargs).Select(m => m.ToTestDisplayString())); Assert.Empty(CSharpExtensions.GetMemberGroup(model, baseWithargs).Select(m => m.ToTestDisplayString())); Assert.False(model.TryGetSpeculativeSemanticModel(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer, out _)); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativePrimaryInitializer); Assert.Equal(SymbolInfo.None, symbolInfo); symbolInfo = model.GetSpeculativeSymbolInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativeBaseInitializer, SpeculativeBindingOption.BindAsExpression); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); symbolInfo = CSharpExtensions.GetSpeculativeSymbolInfo(model, baseWithargs.ArgumentList.OpenParenToken.SpanStart, speculativeBaseInitializer); Assert.Equal("Base..ctor(System.Int32 X)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(TypeInfo.None, model.GetSpeculativeTypeInfo(baseWithargs.ArgumentList.OpenParenToken.SpanStart, (SyntaxNode)speculativePrimaryInitializer, SpeculativeBindingOption.BindAsExpression)); } } [Fact] public void Equality_02() { var source = @"using static System.Console; record C; class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(y) && x.GetHashCode() == y.GetHashCode()); WriteLine(((object)x).Equals(y)); WriteLine(((System.IEquatable<C>)x).Equals(y)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var ordinaryMethods = comp.GetMember<NamedTypeSymbol>("C").GetMembers().OfType<MethodSymbol>().Where(m => m.MethodKind == MethodKind.Ordinary).ToArray(); Assert.Equal(6, ordinaryMethods.Length); foreach (var m in ordinaryMethods) { Assert.True(m.IsImplicitlyDeclared); } var verifier = CompileAndVerify(comp, expectedOutput: @"True True True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(object)", @"{ // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: isinst ""C"" IL_0007: callvirt ""bool C.Equals(C)"" IL_000c: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ret }"); } [Fact] public void Equality_03() { var source = @"using static System.Console; record C { private static int _nextId = 0; private int _id; public C() { _id = _nextId++; } } class Program { static void Main() { var x = new C(); var y = new C(); WriteLine(x.Equals(x)); WriteLine(x.Equals(y)); WriteLine(y.Equals(y)); } }"; var verifier = CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics(); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type C.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type C.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int C._id"" IL_0025: ldarg.1 IL_0026: ldfld ""int C._id"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: call ""System.Collections.Generic.EqualityComparer<System.Type> System.Collections.Generic.EqualityComparer<System.Type>.Default.get"" IL_0005: ldarg.0 IL_0006: callvirt ""System.Type C.EqualityContract.get"" IL_000b: callvirt ""int System.Collections.Generic.EqualityComparer<System.Type>.GetHashCode(System.Type)"" IL_0010: ldc.i4 0xa5555529 IL_0015: mul IL_0016: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001b: ldarg.0 IL_001c: ldfld ""int C._id"" IL_0021: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_0026: add IL_0027: ret }"); var clone = ((CSharpCompilation)verifier.Compilation).GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName); Assert.Equal(Accessibility.Public, clone.DeclaredAccessibility); Assert.False(clone.IsOverride); Assert.True(clone.IsVirtual); Assert.False(clone.IsAbstract); Assert.False(clone.IsSealed); Assert.True(clone.IsImplicitlyDeclared); } [Fact] public void Equality_04() { var source = @"using static System.Console; record A; record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } class Program { static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(new A().Equals(NewB1(1))); WriteLine(NewB1(1).Equals(new A())); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(new A().Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(new A())); WriteLine(((A)NewB2(1)).Equals(NewB2(1)) && ((A)NewB2(1)).GetHashCode() == NewB2(1).GetHashCode()); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False False False False False True True").VerifyDiagnostics( // (3,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(3, 15), // (8,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(8, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B1.<P>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B1.<P>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int B1.<P>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_05() { var source = @"using static System.Console; record A(int P) { internal A() : this(0) { } // Use record base call syntax instead internal int P { get; set; } // Use record base call syntax instead } record B1(int P) : A { internal B1() : this(0) { } // Use record base call syntax instead } record B2(int P) : A { internal B2() : this(0) { } // Use record base call syntax instead } class Program { static A NewA(int p) => new A { P = p }; // Use record base call syntax instead static B1 NewB1(int p) => new B1 { P = p }; // Use record base call syntax instead static B2 NewB2(int p) => new B2 { P = p }; // Use record base call syntax instead static void Main() { WriteLine(NewA(1).Equals(NewA(2))); WriteLine(NewA(1).Equals(NewA(1)) && NewA(1).GetHashCode() == NewA(1).GetHashCode()); WriteLine(NewA(1).Equals(NewB1(1))); WriteLine(NewB1(1).Equals(NewA(1))); WriteLine(NewB1(1).Equals(NewB2(1))); WriteLine(NewA(1).Equals((A)NewB2(1))); WriteLine(((A)NewB2(1)).Equals(NewA(1))); WriteLine(((A)NewB2(1)).Equals(NewB2(1))); WriteLine(NewB2(1).Equals((A)NewB2(1))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"False True False False False False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record A(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (7,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B1(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(7, 15), // (11,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record B2(int P) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(11, 15) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<P>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<P>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B1.Equals(B1)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); verifier.VerifyIL("B1.GetHashCode()", @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""int A.GetHashCode()"" IL_0006: ret }"); } [Fact] public void Equality_06() { var source = @" using System; using static System.Console; record A; record B : A { protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().First(); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True True False False True False False False True False False True True").VerifyDiagnostics( // (8,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(8, 25) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_07() { var source = @"using System; using static System.Console; record A; record B : A; record C : B; class Program { static void Main() { WriteLine(new A().Equals(new A())); WriteLine(new A().Equals(new B())); WriteLine(new A().Equals(new C())); WriteLine(new B().Equals(new A())); WriteLine(new B().Equals(new B())); WriteLine(new B().Equals(new C())); WriteLine(new C().Equals(new A())); WriteLine(new C().Equals(new B())); WriteLine(new C().Equals(new C())); WriteLine(((A)new B()).Equals(new A())); WriteLine(((A)new B()).Equals(new B())); WriteLine(((A)new B()).Equals(new C())); WriteLine(((A)new C()).Equals(new A())); WriteLine(((A)new C()).Equals(new B())); WriteLine(((A)new C()).Equals(new C())); WriteLine(((B)new C()).Equals(new A())); WriteLine(((B)new C()).Equals(new B())); WriteLine(((B)new C()).Equals(new C())); WriteLine(new C().Equals((A)new C())); WriteLine(((IEquatable<A>)new B()).Equals(new A())); WriteLine(((IEquatable<A>)new B()).Equals(new B())); WriteLine(((IEquatable<A>)new B()).Equals(new C())); WriteLine(((IEquatable<A>)new C()).Equals(new A())); WriteLine(((IEquatable<A>)new C()).Equals(new B())); WriteLine(((IEquatable<A>)new C()).Equals(new C())); WriteLine(((IEquatable<B>)new C()).Equals(new A())); WriteLine(((IEquatable<B>)new C()).Equals(new B())); WriteLine(((IEquatable<B>)new C()).Equals(new C())); WriteLine(((IEquatable<C>)new C()).Equals(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False True False False False True False False True True False True False False False True False False True True").VerifyDiagnostics(); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.get_EqualityContract"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A." + WellKnownMemberNames.CloneMethodName), isOverride: false); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C." + WellKnownMemberNames.CloneMethodName), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.GetHashCode"), isOverride: true); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("C.GetHashCode"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); ImmutableArray<Symbol> cEquals = comp.GetMembers("C.Equals"); VerifyVirtualMethods(cEquals, ("System.Boolean C.Equals(C? other)", false), ("System.Boolean C.Equals(B? other)", true), ("System.Boolean C.Equals(System.Object? obj)", true)); var baseEquals = cEquals[1]; Assert.Equal("System.Boolean C.Equals(B? other)", baseEquals.ToTestDisplayString()); Assert.Equal(Accessibility.Public, baseEquals.DeclaredAccessibility); Assert.True(baseEquals.IsOverride); Assert.True(baseEquals.IsSealed); Assert.True(baseEquals.IsImplicitlyDeclared); } private static void VerifyVirtualMethod(MethodSymbol method, bool isOverride) { Assert.Equal(!isOverride, method.IsVirtual); Assert.Equal(isOverride, method.IsOverride); Assert.True(method.IsMetadataVirtual()); Assert.Equal(!isOverride, method.IsMetadataNewSlot()); } private static void VerifyVirtualMethods(ImmutableArray<Symbol> members, params (string displayString, bool isOverride)[] values) { Assert.Equal(members.Length, values.Length); for (int i = 0; i < members.Length; i++) { var method = (MethodSymbol)members[i]; (string displayString, bool isOverride) = values[i]; Assert.Equal(displayString, method.ToTestDisplayString(includeNonNullable: true)); VerifyVirtualMethod(method, isOverride); } } [WorkItem(44895, "https://github.com/dotnet/roslyn/issues/44895")] [Fact] public void Equality_08() { var source = @" using System; using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B : A { internal B() { } // Use record base call syntax instead internal B(int X, int Y) : base(X) { this.Y = Y; } internal int Y { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B b) => base.Equals((A)b); } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3)) && NewC(1, 2, 3).GetHashCode() == NewC(1, 2, 3).GetHashCode()); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. var verifier = CompileAndVerify(source, expectedOutput: @"True True False False True False False False True False True False False True False False False True False False True True").VerifyDiagnostics( // (4,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(4, 14), // (15,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(15, 25), // (17,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(17, 14), // (17,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(17, 21), // (17,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(17, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); // https://github.com/dotnet/roslyn/issues/44895: C.Equals() should compare B.Y. verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.GetHashCode()", @"{ // Code size 30 (0x1e) .maxstack 3 IL_0000: ldarg.0 IL_0001: call ""int B.GetHashCode()"" IL_0006: ldc.i4 0xa5555529 IL_000b: mul IL_000c: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0011: ldarg.0 IL_0012: ldfld ""int C.<Z>k__BackingField"" IL_0017: callvirt ""int System.Collections.Generic.EqualityComparer<int>.GetHashCode(int)"" IL_001c: add IL_001d: ret }"); } [Fact] public void Equality_09() { var source = @"using static System.Console; record A(int X) { internal A() : this(0) { } // Use record base call syntax instead internal int X { get; set; } // Use record base call syntax instead } record B(int X, int Y) : A { internal B() : this(0, 0) { } // Use record base call syntax instead internal int Y { get; set; } } record C(int X, int Y, int Z) : B { internal C() : this(0, 0, 0) { } // Use record base call syntax instead internal int Z { get; set; } // Use record base call syntax instead } class Program { static A NewA(int x) => new A { X = x }; // Use record base call syntax instead static B NewB(int x, int y) => new B { X = x, Y = y }; static C NewC(int x, int y, int z) => new C { X = x, Y = y, Z = z }; static void Main() { WriteLine(NewA(1).Equals(NewA(1))); WriteLine(NewA(1).Equals(NewB(1, 2))); WriteLine(NewA(1).Equals(NewC(1, 2, 3))); WriteLine(NewB(1, 2).Equals(NewA(1))); WriteLine(NewB(1, 2).Equals(NewB(1, 2))); WriteLine(NewB(1, 2).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewA(1))); WriteLine(NewC(1, 2, 3).Equals(NewB(1, 2))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(4, 2, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 3))); WriteLine(NewC(1, 2, 3).Equals(NewC(1, 4, 4))); WriteLine(((A)NewB(1, 2)).Equals(NewA(1))); WriteLine(((A)NewB(1, 2)).Equals(NewB(1, 2))); WriteLine(((A)NewB(1, 2)).Equals(NewC(1, 2, 3))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((A)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewA(1))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewB(1, 2))); WriteLine(((B)NewC(1, 2, 3)).Equals(NewC(1, 2, 3))); WriteLine(NewC(1, 2, 3).Equals((A)NewC(1, 2, 3))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().ElementAt(1); Assert.Equal("B", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False False True False False False True False False False False True False False False True False False True True").VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (7,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(7, 14), // (7,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record B(int X, int Y) : A Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(7, 21), // (12,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(12, 14), // (12,21): warning CS8907: Parameter 'Y' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Y").WithArguments("Y").WithLocation(12, 21), // (12,28): warning CS8907: Parameter 'Z' is unread. Did you forget to use it to initialize the property with that name? // record C(int X, int Y, int Z) : B Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "Z").WithArguments("Z").WithLocation(12, 28) ); verifier.VerifyIL("A.Equals(A)", @"{ // Code size 53 (0x35) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0033 IL_0004: ldarg.1 IL_0005: brfalse.s IL_0031 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: brfalse.s IL_0031 IL_001a: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_001f: ldarg.0 IL_0020: ldfld ""int A.<X>k__BackingField"" IL_0025: ldarg.1 IL_0026: ldfld ""int A.<X>k__BackingField"" IL_002b: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0030: ret IL_0031: ldc.i4.0 IL_0032: ret IL_0033: ldc.i4.1 IL_0034: ret }"); verifier.VerifyIL("B.Equals(A)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A.Equals(A)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int B.<Y>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int B.<Y>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); verifier.VerifyIL("C.Equals(B)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("C.Equals(C)", @"{ // Code size 40 (0x28) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_0026 IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool B.Equals(B)"" IL_000b: brfalse.s IL_0024 IL_000d: call ""System.Collections.Generic.EqualityComparer<int> System.Collections.Generic.EqualityComparer<int>.Default.get"" IL_0012: ldarg.0 IL_0013: ldfld ""int C.<Z>k__BackingField"" IL_0018: ldarg.1 IL_0019: ldfld ""int C.<Z>k__BackingField"" IL_001e: callvirt ""bool System.Collections.Generic.EqualityComparer<int>.Equals(int, int)"" IL_0023: ret IL_0024: ldc.i4.0 IL_0025: ret IL_0026: ldc.i4.1 IL_0027: ret }"); } [Fact] public void Equality_11() { var source = @"using System; record A { protected virtual Type EqualityContract => typeof(object); } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { Console.WriteLine(new A().Equals(new A())); Console.WriteLine(new A().Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new A())); Console.WriteLine(new B1((object)null).Equals(new B1((object)null))); Console.WriteLine(new B1((object)null).Equals(new B2((object)null))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False False True False").VerifyDiagnostics(); } [Fact] public void Equality_12() { var source = @"using System; abstract record A { public A() { } protected abstract Type EqualityContract { get; } } record B1(object P) : A; record B2(object P) : A; class Program { static void Main() { var b1 = new B1((object)null); var b2 = new B2((object)null); Console.WriteLine(b1.Equals(b1)); Console.WriteLine(b1.Equals(b2)); Console.WriteLine(((A)b1).Equals(b1)); Console.WriteLine(((A)b1).Equals(b2)); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False").VerifyDiagnostics(); } [Fact] public void Equality_13() { var source = @"record A { protected System.Type EqualityContract => typeof(A); } record B : A; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,27): error CS8872: 'A.EqualityContract' must allow overriding because the containing record is not sealed. // protected System.Type EqualityContract => typeof(A); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("A.EqualityContract").WithLocation(3, 27), // (5,8): error CS0506: 'B.EqualityContract': cannot override inherited member 'A.EqualityContract' because it is not marked virtual, abstract, or override // record B : A; Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.EqualityContract", "A.EqualityContract").WithLocation(5, 8)); } [Fact] public void Equality_14() { var source = @"record A; record B : A { protected sealed override System.Type EqualityContract => typeof(B); } record C : B; "; var comp = CreateCompilation(source, targetFramework: TargetFramework.StandardLatest); comp.VerifyDiagnostics( // (4,43): error CS8872: 'B.EqualityContract' must allow overriding because the containing record is not sealed. // protected sealed override System.Type EqualityContract => typeof(B); Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "EqualityContract").WithArguments("B.EqualityContract").WithLocation(4, 43), // (6,8): error CS0239: 'C.EqualityContract': cannot override inherited member 'B.EqualityContract' because it is sealed // record C : B; Diagnostic(ErrorCode.ERR_CantOverrideSealed, "C").WithArguments("C.EqualityContract", "B.EqualityContract").WithLocation(6, 8)); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); string expectedClone = comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses ? "B B." + WellKnownMemberNames.CloneMethodName + "()" : "A B." + WellKnownMemberNames.CloneMethodName + "()"; var actualMembers = comp.GetMember<NamedTypeSymbol>("B").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "System.Type B.EqualityContract { get; }", "System.Type B.EqualityContract.get", "System.String B.ToString()", "System.Boolean B." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B.op_Inequality(B? left, B? right)", "System.Boolean B.op_Equality(B? left, B? right)", "System.Int32 B.GetHashCode()", "System.Boolean B.Equals(System.Object? obj)", "System.Boolean B.Equals(A? other)", "System.Boolean B.Equals(B? other)", expectedClone, "B..ctor(B original)", "B..ctor()", }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact] public void Equality_15() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(A); public virtual bool Equals(B1 o) => base.Equals((A)o); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(B2); public virtual bool Equals(B2 o) => base.Equals((A)o); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(1))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; CompileAndVerify(source, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 o) => base.Equals((A)o); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_16() { var source = @"using System; record A; record B1 : A { public B1(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B1 b) => base.Equals((A)b); } record B2 : A { public B2(int p) { P = p; } public int P { get; set; } protected override Type EqualityContract => typeof(string); public virtual bool Equals(B2 b) => base.Equals((A)b); } class Program { static void Main() { Console.WriteLine(new B1(1).Equals(new B1(2))); Console.WriteLine(new B1(1).Equals(new B2(2))); Console.WriteLine(new B2(1).Equals(new B2(2))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"True False True").VerifyDiagnostics( // (8,25): warning CS8851: 'B1' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B1 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B1").WithLocation(8, 25), // (15,25): warning CS8851: 'B2' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B2 b) => base.Equals((A)b); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B2").WithLocation(15, 25) ); } [Fact] public void Equality_17() { var source = @"using static System.Console; record A; record B1(int P) : A { } record B2(int P) : A { } class Program { static void Main() { WriteLine(new B1(1).Equals(new B1(1))); WriteLine(new B1(1).Equals(new B1(2))); WriteLine(new B2(3).Equals(new B2(3))); WriteLine(new B2(3).Equals(new B2(4))); WriteLine(((A)new B1(1)).Equals(new B1(1))); WriteLine(((A)new B1(1)).Equals(new B1(2))); WriteLine(((A)new B2(3)).Equals(new B2(3))); WriteLine(((A)new B2(3)).Equals(new B2(4))); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); // init-only is unverifiable CompileAndVerify(comp, verify: Verification.Skipped, expectedOutput: @"True False True False True False True False").VerifyDiagnostics(); var actualMembers = comp.GetMember<NamedTypeSymbol>("B1").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "B1..ctor(System.Int32 P)", "System.Type B1.EqualityContract.get", "System.Type B1.EqualityContract { get; }", "System.Int32 B1.<P>k__BackingField", "System.Int32 B1.P.get", "void modreq(System.Runtime.CompilerServices.IsExternalInit) B1.P.init", "System.Int32 B1.P { get; init; }", "System.String B1.ToString()", "System.Boolean B1." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean B1.op_Inequality(B1? left, B1? right)", "System.Boolean B1.op_Equality(B1? left, B1? right)", "System.Int32 B1.GetHashCode()", "System.Boolean B1.Equals(System.Object? obj)", "System.Boolean B1.Equals(A? other)", "System.Boolean B1.Equals(B1? other)", "A B1." + WellKnownMemberNames.CloneMethodName + "()", "B1..ctor(B1 original)", "void B1.Deconstruct(out System.Int32 P)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Theory] [InlineData(false)] [InlineData(true)] public void Equality_18(bool useCompilationReference) { var sourceA = @"public record A;"; var comp = CreateCompilation(sourceA); comp.VerifyDiagnostics(); var refA = useCompilationReference ? comp.ToMetadataReference() : comp.EmitToImageReference(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("A.get_EqualityContract"), isOverride: false); VerifyVirtualMethods(comp.GetMembers("A.Equals"), ("System.Boolean A.Equals(A? other)", false), ("System.Boolean A.Equals(System.Object? obj)", true)); var sourceB = @"record B : A;"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); VerifyVirtualMethod(comp.GetMember<MethodSymbol>("B.get_EqualityContract"), isOverride: true); VerifyVirtualMethods(comp.GetMembers("B.Equals"), ("System.Boolean B.Equals(B? other)", false), ("System.Boolean B.Equals(A? other)", true), ("System.Boolean B.Equals(System.Object? obj)", true)); } [Fact] public void Equality_19() { var source = @"using static System.Console; record A<T>; record B : A<int>; class Program { static void Main() { WriteLine(new A<int>().Equals(new A<int>())); WriteLine(new A<int>().Equals(new B())); WriteLine(new B().Equals(new A<int>())); WriteLine(new B().Equals(new B())); WriteLine(((A<int>)new B()).Equals(new A<int>())); WriteLine(((A<int>)new B()).Equals(new B())); WriteLine(new B().Equals((A<int>)new B())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"True False False True False True True").VerifyDiagnostics(); verifier.VerifyIL("A<T>.Equals(A<T>)", @"{ // Code size 29 (0x1d) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_001b IL_0004: ldarg.1 IL_0005: brfalse.s IL_0019 IL_0007: ldarg.0 IL_0008: callvirt ""System.Type A<T>.EqualityContract.get"" IL_000d: ldarg.1 IL_000e: callvirt ""System.Type A<T>.EqualityContract.get"" IL_0013: call ""bool System.Type.op_Equality(System.Type, System.Type)"" IL_0018: ret IL_0019: ldc.i4.0 IL_001a: ret IL_001b: ldc.i4.1 IL_001c: ret }"); verifier.VerifyIL("B.Equals(A<int>)", @"{ // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: callvirt ""bool object.Equals(object)"" IL_0007: ret }"); verifier.VerifyIL("B.Equals(B)", @"{ // Code size 14 (0xe) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: beq.s IL_000c IL_0004: ldarg.0 IL_0005: ldarg.1 IL_0006: call ""bool A<int>.Equals(A<int>)"" IL_000b: ret IL_000c: ldc.i4.1 IL_000d: ret }"); } [Fact] public void Equality_20() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__GetHashCode); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.GetHashCode' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "GetHashCode").WithLocation(2, 1) ); } [Fact] public void Equality_21() { var source = @" record C; "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C; Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "record C;").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1) ); } [Fact] [WorkItem(44988, "https://github.com/dotnet/roslyn/issues/44988")] public void Equality_22() { var source = @" record C { int x = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseDll); comp.MakeMemberMissing(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); comp.VerifyEmitDiagnostics( // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (2,1): error CS0656: Missing compiler required member 'System.Collections.Generic.EqualityComparer`1.get_Default' // record C Diagnostic(ErrorCode.ERR_MissingPredefinedMember, @"record C { int x = 0; }").WithArguments("System.Collections.Generic.EqualityComparer`1", "get_Default").WithLocation(2, 1), // (4,9): warning CS0414: The field 'C.x' is assigned but its value is never used // int x = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(4, 9) ); } [Fact] public void IEquatableT_01() { var source = @"record A<T>; record B : A<int>; class Program { static void F<T>(System.IEquatable<T> t) { } static void M<T>() { F(new A<T>()); F(new B()); F<A<int>>(new B()); F<B>(new B()); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0411: The type arguments for method 'Program.F<T>(IEquatable<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(new B()); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.IEquatable<T>)").WithLocation(11, 9)); } [Fact] public void IEquatableT_02() { var source = @"using System; record A; record B<T> : A; record C : B<int>; class Program { static string F<T>(IEquatable<T> t) { return typeof(T).Name; } static void Main() { Console.WriteLine(F(new A())); Console.WriteLine(F<A>(new C())); Console.WriteLine(F<B<int>>(new C())); Console.WriteLine(F<C>(new C())); } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A A B`1 C").VerifyDiagnostics(); } [Fact] public void IEquatableT_03() { var source = @"#nullable enable using System; record A<T> : IEquatable<A<T>> { } record B : A<object>, IEquatable<A<object>>, IEquatable<B?>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B?>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_04() { var source = @"using System; record A<T> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)").VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: 'B' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_05() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } public virtual bool Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { public virtual bool Equals(B other) => Report(""B.Equals(B)""); } record C : A<object>, IEquatable<A<object>>, IEquatable<C> { } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(B) B.Equals(B) B.Equals(B) A<T>.Equals(A<T>) B.Equals(B) B.Equals(B)", symbolValidator: m => { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("B.Equals(B)", b.FindImplementationForInterfaceMember(b.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); var c = m.GlobalNamespace.GetTypeMember("C"); Assert.Equal("C.Equals(C?)", c.FindImplementationForInterfaceMember(c.InterfacesNoUseSiteDiagnostics()[1].GetMember("Equals")).ToDisplayString()); }).VerifyDiagnostics( // (5,25): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(A<T> other) => Report("A<T>.Equals(A<T>)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(5, 25), // (9,25): warning CS8851: '{B}' defines 'Equals' but not 'GetHashCode' // public virtual bool Equals(B other) => Report("B.Equals(B)"); Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("B").WithLocation(9, 25) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_06() { var source = @"using System; record A<T> : IEquatable<A<T>> { internal static bool Report(string s) { Console.WriteLine(s); return false; } bool IEquatable<A<T>>.Equals(A<T> other) => Report(""A<T>.Equals(A<T>)""); } record B : A<object>, IEquatable<A<object>>, IEquatable<B> { bool IEquatable<A<object>>.Equals(A<object> other) => Report(""B.Equals(A<object>)""); bool IEquatable<B>.Equals(B other) => Report(""B.Equals(B)""); } class Program { static void Main() { var a = new A<object>(); var b = new B(); _ = a.Equals(b); _ = ((A<object>)b).Equals(b); _ = b.Equals(a); _ = b.Equals(b); _ = ((IEquatable<A<object>>)a).Equals(b); _ = ((IEquatable<A<object>>)b).Equals(b); _ = ((IEquatable<B>)b).Equals(b); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: @"A<T>.Equals(A<T>) B.Equals(A<object>) B.Equals(B)").VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_07() { var source = @"using System; record A<T> : IEquatable<B1>, IEquatable<B2> { bool IEquatable<B1>.Equals(B1 other) => false; bool IEquatable<B2>.Equals(B2 other) => false; } record B1 : A<object>; record B2 : A<int>; "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<B2>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B1"); AssertEx.Equal(new[] { "System.IEquatable<B1>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B2>", "System.IEquatable<A<System.Object>>", "System.IEquatable<B1>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B2"); AssertEx.Equal(new[] { "System.IEquatable<B2>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<B1>", "System.IEquatable<A<System.Int32>>", "System.IEquatable<B2>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_08() { var source = @"interface I<T> { } record A<T> : I<A<T>> { } record B : A<object>, I<A<object>>, I<B> { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "I<A<T>>", "System.IEquatable<A<T>>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Object>>", "I<A<System.Object>>", "I<B>", "System.IEquatable<B>" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_09() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T>; record B : A<int>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8) ); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_10() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A<T> : System.IEquatable<A<T>>; record B : A<int>, System.IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(1, 8), // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(1, 8), // (1,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(1, 8), // (1,22): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record A<T> : System.IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<A<T>>").WithArguments("IEquatable<>", "System").WithLocation(1, 22), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(2, 8), // (2,27): error CS0234: The type or namespace name 'IEquatable<>' does not exist in the namespace 'System' (are you missing an assembly reference?) // record B : A<int>, System.IEquatable<B>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IEquatable<B>").WithArguments("IEquatable<>", "System").WithLocation(2, 27)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "System.IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_11() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"using System; record A<T> : IEquatable<A<T>>; record B : A<int>, IEquatable<B>; "; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,1): hidden CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithLocation(1, 1), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.IEquatable`1").WithLocation(2, 8), // (2,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,15): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record A<T> : IEquatable<A<T>>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<A<T>>").WithArguments("IEquatable<>").WithLocation(2, 15), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.IEquatable`1' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.IEquatable`1").WithLocation(3, 8), // (3,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "B").WithArguments("System.Type").WithLocation(3, 8), // (3,20): error CS0246: The type or namespace name 'IEquatable<>' could not be found (are you missing a using directive or an assembly reference?) // record B : A<int>, IEquatable<B>; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IEquatable<B>").WithArguments("IEquatable<>").WithLocation(3, 20)); var type = comp.GetMember<NamedTypeSymbol>("A"); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<T>>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); type = comp.GetMember<NamedTypeSymbol>("B"); AssertEx.Equal(new[] { "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.InterfacesNoUseSiteDiagnostics().ToTestDisplayStrings()); AssertEx.Equal(new[] { "System.IEquatable<A<System.Int32>>[missing]", "IEquatable<B>", "System.IEquatable<B>[missing]" }, type.AllInterfacesNoUseSiteDiagnostics.ToTestDisplayStrings()); } [Fact] public void IEquatableT_12() { var source0 = @"namespace System { public class Object { public virtual bool Equals(object other) => false; public virtual int GetHashCode() => 0; public virtual string ToString() => """"; } public class String { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Int32 { } public interface IEquatable<T> { bool Equals(T other); void Other(); } } namespace System.Text { public class StringBuilder { public StringBuilder Append(string s) => null; public StringBuilder Append(object s) => null; } }"; var comp = CreateEmptyCompilation(source0); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source1 = @"record A; class Program { static void Main() { System.IEquatable<A> a = new A(); _ = a.Equals(null); } }"; comp = CreateEmptyCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (1,8): error CS0518: Predefined type 'System.Type' is not defined or imported // record A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "A").WithArguments("System.Type").WithLocation(1, 8), // (1,8): error CS0535: 'A' does not implement interface member 'IEquatable<A>.Other()' // record A; Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("A", "System.IEquatable<A>.Other()").WithLocation(1, 8)); } [Fact] public void IEquatableT_13() { var source = @"record A { internal virtual bool Equals(A other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (1,8): error CS0737: 'A' does not implement interface member 'IEquatable<A>.Equals(A)'. 'A.Equals(A)' cannot implement an interface member because it is not public. // record A Diagnostic(ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, "A").WithArguments("A", "System.IEquatable<A>.Equals(A)", "A.Equals(A)").WithLocation(1, 8), // (3,27): error CS8873: Record member 'A.Equals(A)' must be public. // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NonPublicAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 27), // (3,27): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // internal virtual bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 27) ); } [Fact] public void IEquatableT_14() { var source = @"record A { public bool Equals(A other) => false; } record B : A { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,17): error CS8872: 'A.Equals(A)' must allow overriding because the containing record is not sealed. // public bool Equals(A other) => false; Diagnostic(ErrorCode.ERR_NotOverridableAPIInRecord, "Equals").WithArguments("A.Equals(A)").WithLocation(3, 17), // (3,17): warning CS8851: 'A' defines 'Equals' but not 'GetHashCode' // public bool Equals(A other) => false; Diagnostic(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, "Equals").WithArguments("A").WithLocation(3, 17), // (5,8): error CS0506: 'B.Equals(A?)': cannot override inherited member 'A.Equals(A)' because it is not marked virtual, abstract, or override // record B : A Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "B").WithArguments("B.Equals(A?)", "A.Equals(A)").WithLocation(5, 8)); } [WorkItem(45026, "https://github.com/dotnet/roslyn/issues/45026")] [Fact] public void IEquatableT_15() { var source = @"using System; record R { bool IEquatable<R>.Equals(R other) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void IEquatableT_16() { var source = @"using System; class A<T> { record B<U> : IEquatable<B<T>> { bool IEquatable<B<T>>.Equals(B<T> other) => false; bool IEquatable<B<U>>.Equals(B<U> other) => false; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,12): error CS0695: 'A<T>.B<U>' cannot implement both 'IEquatable<A<T>.B<T>>' and 'IEquatable<A<T>.B<U>>' because they may unify for some type parameter substitutions // record B<U> : IEquatable<B<T>> Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "B").WithArguments("A<T>.B<U>", "System.IEquatable<A<T>.B<T>>", "System.IEquatable<A<T>.B<U>>").WithLocation(4, 12)); } [Fact] public void InterfaceImplementation() { var source = @" interface I { int P1 { get; init; } int P2 { get; init; } int P3 { get; set; } } record R(int P1) : I { public int P2 { get; init; } int I.P3 { get; set; } public static void Main() { I r = new R(42) { P2 = 43 }; r.P3 = 44; System.Console.Write((r.P1, r.P2, r.P3)); } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyEmitDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44)", verify: Verification.Skipped /* init-only */); } [Fact] public void Initializers_01() { var src = @" using System; record C(int X) { int Z = X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); var recordDeclaration = tree.GetRoot().DescendantNodes().OfType<RecordDeclarationSyntax>().Single(); Assert.Equal("C", recordDeclaration.Identifier.ValueText); Assert.Null(model.GetOperation(recordDeclaration)); } [Fact] public void Initializers_02() { var src = @" record C(int X) { static int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,20): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // static int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 20) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_03() { var src = @" record C(int X) { const int Z = X + 1; }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (4,19): error CS0236: A field initializer cannot reference the non-static field, method, or property 'C.X' // const int Z = X + 1; Diagnostic(ErrorCode.ERR_FieldInitRefNonstatic, "X").WithArguments("C.X").WithLocation(4, 19) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("= X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Property, symbol!.Kind); Assert.Equal("System.Int32 C.X { get; init; }", symbol.ToTestDisplayString()); Assert.Equal("C", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("System.Int32 C.Z", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_04() { var src = @" using System; record C(int X) { Func<int> Z = () => X + 1; public static void Main() { var c = new C(1); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @"2").VerifyDiagnostics(); var comp = CreateCompilation(src); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var x = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "X").First(); Assert.Equal("() => X + 1", x.Parent!.Parent!.ToString()); var symbol = model.GetSymbolInfo(x).Symbol; Assert.Equal(SymbolKind.Parameter, symbol!.Kind); Assert.Equal("System.Int32 X", symbol.ToTestDisplayString()); Assert.Equal("C..ctor(System.Int32 X)", symbol.ContainingSymbol.ToTestDisplayString()); Assert.Equal("lambda expression", model.GetEnclosingSymbol(x.SpanStart).ToTestDisplayString()); Assert.Contains(symbol, model.LookupSymbols(x.SpanStart, name: "X")); Assert.Contains("X", model.LookupNames(x.SpanStart)); } [Fact] public void Initializers_05() { var src = @" using System; record Base { public Base(Func<int> X) { Console.WriteLine(X()); } public Base() {} } record C(int X) : Base(() => 100 + X++) { Func<int> Y = () => 200 + X++; Func<int> Z = () => 300 + X++; public static void Main() { var c = new C(1); Console.WriteLine(c.Y()); Console.WriteLine(c.Z()); } }"; var verifier = CompileAndVerify(src, expectedOutput: @" 101 202 303 ").VerifyDiagnostics(); } [Fact] public void SynthesizedRecordPointerProperty() { var src = @" record R(int P1, int* P2, delegate*<int> P3);"; var comp = CreateCompilation(src); var p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P1"); Assert.False(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P2"); Assert.True(p.HasPointerType); p = comp.GlobalNamespace.GetTypeMember("R").GetMember<SourcePropertySymbolBase>("P3"); Assert.True(p.HasPointerType); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut() { var src = @" record R(ref int P1, out int P2); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0177: The out parameter 'P2' must be assigned to before control leaves the current method // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_ParamUnassigned, "R").WithArguments("P2").WithLocation(2, 8), // (2,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(2, 10), // (2,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(2, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_RefOrOut_WithBase() { var src = @" record Base(int I); record R(ref int P1, out int P2) : Base(P2 = 1); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (3,10): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "ref").WithLocation(3, 10), // (3,22): error CS0631: ref and out are not valid in this context // record R(ref int P1, out int P2) : Base(P2 = 1); Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(3, 22) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_In() { var src = @" record R(in int P1); public class C { public static void Main() { var r = new R(42); int i = 43; var r2 = new R(in i); System.Console.Write((r.P1, r2.P1)); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(in System.Int32 P1)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_This() { var src = @" record R(this int i); "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,10): error CS0027: Keyword 'this' is not available in the current context // record R(this int i); Diagnostic(ErrorCode.ERR_ThisInBadContext, "this").WithLocation(2, 10) ); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberModifiers_Params() { var src = @" record R(params int[] Array); public class C { public static void Main() { var r = new R(42, 43); var r2 = new R(new[] { 44, 45 }); System.Console.Write((r.Array[0], r.Array[1], r2.Array[0], r2.Array[1])); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "(42, 43, 44, 45)", verify: Verification.Skipped /* init-only */); var actualMembers = comp.GetMember<NamedTypeSymbol>("R").Constructors.ToTestDisplayStrings(); var expectedMembers = new[] { "R..ctor(params System.Int32[] Array)", "R..ctor(R original)" }; AssertEx.Equal(expectedMembers, actualMembers); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue() { var src = @" record R(int P = 42) { public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer() { var src = @" record R(int P = 1) { public int P { get; init; } = 42; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 1) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 16 (0x10) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.s 42 IL_0003: stfld ""int R.<P>k__BackingField"" IL_0008: ldarg.0 IL_0009: call ""object..ctor()"" IL_000e: nop IL_000f: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithoutInitializer() { var src = @" record R(int P = 42) { public int P { get; init; } public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record R(int P = 42) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14) ); var verifier = CompileAndVerify(comp, expectedOutput: "0", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 8 (0x8) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: nop IL_0007: ret }"); } [Fact, WorkItem(45008, "https://github.com/dotnet/roslyn/issues/45008")] public void PositionalMemberDefaultValue_AndPropertyWithInitializer_CopyingParameter() { var src = @" record R(int P = 42) { public int P { get; init; } = P; public static void Main() { var r = new R(); System.Console.Write(r.P); } } "; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("R..ctor(int)", @" { // Code size 15 (0xf) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int R.<P>k__BackingField"" IL_0007: ldarg.0 IL_0008: call ""object..ctor()"" IL_000d: nop IL_000e: ret }"); } [Fact] public void AttributesOnPrimaryConstructorParameters_01() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => a.AttributeClass!.Name is "A" or "B" or "C" or "D")); } } [Fact] public void AttributesOnPrimaryConstructorParameters_02() { string source = @" [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true) ] public class D : System.Attribute { } public record Test( [field: A] [property: B] [param: C] [D] int P1) { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_03() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public abstract int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new[] { "B" }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new[] { "A" }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics(); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_04() { string source = @" [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true) ] public class A : System.Attribute { } public record Test( [method: A] int P1) { [method: A] void M1() {} } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var prop1 = @class.GetMember<PropertySymbol>("P1"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(prop1)); var field1 = @class.GetMember<FieldSymbol>("<P1>k__BackingField"); AssertEx.SetEqual(new string[] { }, getAttributeStrings(field1)); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new string[] { }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (8,6): warning CS0657: 'method' is not a valid attribute location for this declaration. Valid attribute locations for this declaration are 'field, property, param'. All attributes in this block will be ignored. // [method: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "method").WithArguments("method", "field, property, param").WithLocation(8, 6) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_05() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public virtual int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,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. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,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. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_06() { string source = @" [System.AttributeUsage(System.AttributeTargets.Field, AllowMultiple = true) ] public class A : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Property, AllowMultiple = true) ] public class B : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [field: A] [property: B] [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); Assert.Null(@class.GetMember<PropertySymbol>("P1")); Assert.Null(@class.GetMember<FieldSymbol>("<P1>k__BackingField")); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (27,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. // [field: A] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "field").WithArguments("field", "param").WithLocation(27, 6), // (28,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. // [property: B] Diagnostic(ErrorCode.WRN_AttributeLocationOnBadDeclaration, "property").WithArguments("property", "param").WithLocation(28, 6), // (31,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(31, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "A": case "B": case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_07() { string source = @" [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class C : System.Attribute { } [System.AttributeUsage(System.AttributeTargets.Parameter, AllowMultiple = true) ] public class D : System.Attribute { } public abstract record Base { public int P1 { get; init; } } public record Test( [param: C] [D] int P1) : Base { } "; Action<ModuleSymbol> symbolValidator = moduleSymbol => { var @class = moduleSymbol.GlobalNamespace.GetMember<NamedTypeSymbol>("Test"); var param1 = @class.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.AsSingleton()?.Name == "P1").Single().Parameters[0]; AssertEx.SetEqual(new[] { "C", "D" }, getAttributeStrings(param1)); }; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator, parseOptions: TestOptions.Regular9, // init-only is unverifiable verify: Verification.Skipped, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); comp.VerifyDiagnostics( // (20,9): warning CS8907: Parameter 'P1' is unread. Did you forget to use it to initialize the property with that name? // int P1) : Base Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P1").WithArguments("P1").WithLocation(20, 9) ); IEnumerable<string> getAttributeStrings(Symbol symbol) { return GetAttributeStrings(symbol.GetAttributes().Where(a => { switch (a.AttributeClass!.Name) { case "C": case "D": return true; } return false; })); } } [Fact] public void AttributesOnPrimaryConstructorParameters_08() { string source = @" #nullable enable using System.Diagnostics.CodeAnalysis; record C<T>([property: NotNull] T? P1, T? P2) where T : class { protected C(C<T> other) { T x = P1; T y = P2; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(10, 15) ); } [Fact] public void AttributesOnPrimaryConstructorParameters_09_CallerMemberName() { string source = @" using System.Runtime.CompilerServices; record R([CallerMemberName] string S = """"); class C { public static void Main() { var r = new R(); System.Console.Write(r.S); } } "; var comp = CompileAndVerify(new[] { source, IsExternalInitTypeDefinition }, expectedOutput: "Main", parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe, verify: Verification.Skipped /* init-only */); comp.VerifyDiagnostics(); } [Fact] public void RecordWithConstraints_NullableWarning() { var src = @" #nullable enable record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { var r = new R<string?>(""R""); var r2 = new R2<string?>(""R2""); System.Console.Write((r.P, r2.P)); } }"; var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (10,23): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r = new R<string?>("R"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R<T>", "T", "string?").WithLocation(10, 23), // (11,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'R2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var r2 = new R2<string?>("R2"); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("R2<T>", "T", "string?").WithLocation(11, 25) ); CompileAndVerify(comp, expectedOutput: "(R, R2)", verify: Verification.Skipped /* init-only */); } [Fact] public void RecordWithConstraints_ConstraintError() { var src = @" record R<T>(T P) where T : class; record R2<T>(T P) where T : class { } public class C { public static void Main() { _ = new R<int>(1); _ = new R2<int>(2); } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,19): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R<T>' // _ = new R<int>(1); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R<T>", "T", "int").WithLocation(9, 19), // (10,20): error CS0452: The type 'int' must be a reference type in order to use it as parameter 'T' in the generic type or method 'R2<T>' // _ = new R2<int>(2); Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int").WithArguments("R2<T>", "T", "int").WithLocation(10, 20) ); } [Fact] public void AccessCheckProtected03() { CSharpCompilation c = CreateCompilation(@" record X<T> { } record A { } record B { record C : X<C.D.E> { protected record D : A { public record E { } } } } ", targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, c.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (c.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } else { c.VerifyDiagnostics( // (8,12): error CS0060: Inconsistent accessibility: base type 'X<B.C.D.E>' is less accessible than class 'B.C' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("B.C", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0050: Inconsistent accessibility: return type 'X<B.C.D.E>' is less accessible than method 'B.C.<Clone>$()' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisReturnType, "C").WithArguments("B.C.<Clone>$()", "X<B.C.D.E>").WithLocation(8, 12), // (8,12): error CS0051: Inconsistent accessibility: parameter type 'X<B.C.D.E>' is less accessible than method 'B.C.Equals(X<B.C.D.E>?)' // record C : X<C.D.E> Diagnostic(ErrorCode.ERR_BadVisParamType, "C").WithArguments("B.C.Equals(X<B.C.D.E>?)", "X<B.C.D.E>").WithLocation(8, 12) ); } } [Fact] public void TestTargetType_Abstract() { var source = @" abstract record C { void M() { C x0 = new(); var x1 = (C)new(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,16): error CS0144: Cannot create an instance of the abstract type or interface 'C' // C x0 = new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(6, 16), // (7,21): error CS0144: Cannot create an instance of the abstract type or interface 'C' // var x1 = (C)new(); Diagnostic(ErrorCode.ERR_NoNewAbstract, "new()").WithArguments("C").WithLocation(7, 21) ); } [Fact] public void CyclicBases4() { var text = @" record A<T> : B<A<T>> { } record B<T> : A<B<T>> { A<T> F() { return null; } } "; var comp = CreateCompilation(text); comp.GetDeclarationDiagnostics().Verify( // (2,8): error CS0146: Circular base type dependency involving 'B<A<T>>' and 'A<T>' // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_CircularBase, "A").WithArguments("B<A<T>>", "A<T>").WithLocation(2, 8), // (3,8): error CS0146: Circular base type dependency involving 'A<B<T>>' and 'B<T>' // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_CircularBase, "B").WithArguments("A<B<T>>", "B<T>").WithLocation(3, 8), // (2,8): error CS0115: 'A<T>.ToString()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.EqualityContract': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.Equals(object?)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.GetHashCode()': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'A<T>.PrintMembers(StringBuilder)': no suitable method found to override // record A<T> : B<A<T>> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "A").WithArguments("A<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (3,8): error CS0115: 'B<T>.EqualityContract': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.EqualityContract").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.Equals(object?)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.Equals(object?)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.GetHashCode()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.GetHashCode()").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.PrintMembers(StringBuilder)': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 8), // (3,8): error CS0115: 'B<T>.ToString()': no suitable method found to override // record B<T> : A<B<T>> { Diagnostic(ErrorCode.ERR_OverrideNotExpected, "B").WithArguments("B<T>.ToString()").WithLocation(3, 8) ); } [Fact] public void CS0250ERR_CallingBaseFinalizeDeprecated() { var text = @" record B { } record C : B { ~C() { base.Finalize(); // CS0250 } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (10,7): error CS0250: Do not directly call your base type Finalize method. It is called automatically from your destructor. Diagnostic(ErrorCode.ERR_CallingBaseFinalizeDeprecated, "base.Finalize()") ); } [Fact] public void PartialClassWithDifferentTupleNamesInBaseTypes() { var source = @" public record Base<T> { } public partial record C1 : Base<(int a, int b)> { } public partial record C1 : Base<(int notA, int notB)> { } public partial record C2 : Base<(int a, int b)> { } public partial record C2 : Base<(int, int)> { } public partial record C3 : Base<(int a, int b)> { } public partial record C3 : Base<(int a, int b)> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,23): error CS0263: Partial declarations of 'C2' must not specify different base classes // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2").WithLocation(5, 23), // (3,23): error CS0263: Partial declarations of 'C1' must not specify different base classes // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1").WithLocation(3, 23), // (5,23): error CS0115: 'C2.ToString()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.ToString()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.EqualityContract': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.EqualityContract").WithLocation(5, 23), // (5,23): error CS0115: 'C2.Equals(object?)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.Equals(object?)").WithLocation(5, 23), // (5,23): error CS0115: 'C2.GetHashCode()': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.GetHashCode()").WithLocation(5, 23), // (5,23): error CS0115: 'C2.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C2 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C2").WithArguments("C2.PrintMembers(System.Text.StringBuilder)").WithLocation(5, 23), // (3,23): error CS0115: 'C1.ToString()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.ToString()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.EqualityContract': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.EqualityContract").WithLocation(3, 23), // (3,23): error CS0115: 'C1.Equals(object?)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.Equals(object?)").WithLocation(3, 23), // (3,23): error CS0115: 'C1.GetHashCode()': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.GetHashCode()").WithLocation(3, 23), // (3,23): error CS0115: 'C1.PrintMembers(StringBuilder)': no suitable method found to override // public partial record C1 : Base<(int a, int b)> { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "C1").WithArguments("C1.PrintMembers(System.Text.StringBuilder)").WithLocation(3, 23) ); } [Fact] public void CS0267ERR_PartialMisplaced() { var test = @" partial public record C // CS0267 { } "; CreateCompilation(test).VerifyDiagnostics( // (2,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial public class C // CS0267 Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(2, 1)); } [Fact] public void AttributeContainsGeneric() { string source = @" [Goo<int>] class G { } record Goo<T> { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS0616: 'Goo<T>' is not an attribute class // [Goo<int>] Diagnostic(ErrorCode.ERR_NotAnAttributeClass, "Goo<int>").WithArguments("Goo<T>").WithLocation(2, 2) ); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } record A { } record B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void SealedStaticRecord() { var source = @" sealed static record R; "; CreateCompilation(source).VerifyDiagnostics( // (2,22): error CS0106: The modifier 'static' is not valid for this item // sealed static record R; Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 22) ); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" record C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void ConversionToBase() { var source = @" public record Base<T> { } public record Derived : Base<(int a, int b)> { public static explicit operator Base<(int, int)>(Derived x) { return null; } public static explicit operator Derived(Base<(int, int)> x) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,37): error CS0553: 'Derived.explicit operator Derived(Base<(int, int)>)': user-defined conversions to or from a base type are not allowed // public static explicit operator Derived(Base<(int, int)> x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Derived").WithArguments("Derived.explicit operator Derived(Base<(int, int)>)").WithLocation(9, 37), // (5,37): error CS0553: 'Derived.explicit operator Base<(int, int)>(Derived)': user-defined conversions to or from a base type are not allowed // public static explicit operator Base<(int, int)>(Derived x) Diagnostic(ErrorCode.ERR_ConversionWithBase, "Base<(int, int)>").WithArguments("Derived.explicit operator Base<(int, int)>(Derived)").WithLocation(5, 37) ); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public record B { public static implicit operator B(D d) // CS0554 { return null; } } public record D : B {} "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0574ERR_BadDestructorName() { var test = @" namespace x { public record iii { ~iiii(){} public static void Main() { } } } "; CreateCompilation(test).VerifyDiagnostics( // (6,10): error CS0574: Name of destructor must match name of type // ~iiii(){} Diagnostic(ErrorCode.ERR_BadDestructorName, "iiii").WithLocation(6, 10)); } [Fact] public void StaticBasePartial() { var text = @" static record NV { } public partial record C1 { } partial record C1 : NV { } public partial record C1 { } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses) { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } else { comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record NV Diagnostic(ErrorCode.ERR_BadMemberFlag, "NV").WithArguments("static").WithLocation(2, 15), // (6,23): error CS0050: Inconsistent accessibility: return type 'NV' is less accessible than method 'C1.<Clone>$()' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisReturnType, "C1").WithArguments("C1.<Clone>$()", "NV").WithLocation(6, 23), // (6,23): error CS0051: Inconsistent accessibility: parameter type 'NV' is less accessible than method 'C1.Equals(NV?)' // public partial record C1 Diagnostic(ErrorCode.ERR_BadVisParamType, "C1").WithArguments("C1.Equals(NV?)", "NV").WithLocation(6, 23), // (10,16): error CS0060: Inconsistent accessibility: base class 'NV' is less accessible than class 'C1' // partial record C1 : NV Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "NV").WithLocation(10, 16) ); } } [Fact] public void StaticRecordWithConstructorAndDestructor() { var text = @" static record R(int I) { R() : this(0) { } ~R() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,15): error CS0106: The modifier 'static' is not valid for this item // static record R(int I) Diagnostic(ErrorCode.ERR_BadMemberFlag, "R").WithArguments("static").WithLocation(2, 15) ); } [Fact] public void RecordWithPartialMethodExplicitImplementation() { var source = @"record R { partial void M(); }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0751: A partial method must be declared within a partial type // partial void M(); Diagnostic(ErrorCode.ERR_PartialMethodOnlyInPartialClass, "M").WithLocation(3, 18) ); } [Fact] public void RecordWithMultipleBaseTypes() { var source = @" record Base1; record Base2; record R : Base1, Base2 { }"; CreateCompilation(source).VerifyDiagnostics( // (4,19): error CS1721: Class 'R' cannot have multiple base classes: 'Base1' and 'Base2' // record R : Base1, Base2 Diagnostic(ErrorCode.ERR_NoMultipleInheritance, "Base2").WithArguments("R", "Base1", "Base2").WithLocation(4, 19) ); } [Fact] public void RecordWithInterfaceBeforeBase() { var source = @" record Base; interface I { } record R : I, Base; "; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS1722: Base class 'Base' must come before any interfaces // record R : I, Base; Diagnostic(ErrorCode.ERR_BaseClassMustBeFirst, "Base").WithArguments("Base").WithLocation(4, 15) ); } [Fact] public void RecordLoadedInVisualBasicDisplaysAsClass() { var src = @" public record A; "; var compRef = CreateCompilation(src).EmitToImageReference(); var vbComp = CreateVisualBasicCompilation("", referencedAssemblies: new[] { compRef }); var symbol = vbComp.GlobalNamespace.GetTypeMember("A"); Assert.False(symbol.IsRecord); Assert.Equal("class A", SymbolDisplay.ToDisplayString(symbol, SymbolDisplayFormat.TestFormat.AddKindOptions(SymbolDisplayKindOptions.IncludeTypeKeyword))); } [Fact] public void AnalyzerActions_01() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} class Attr1 : System.Attribute {} class Attr2 : System.Attribute {} class Attr3 : System.Attribute {} "; var analyzer = new AnalyzerActions_01_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount18); Assert.Equal(1, analyzer.FireCount19); Assert.Equal(1, analyzer.FireCount20); Assert.Equal(1, analyzer.FireCount21); Assert.Equal(1, analyzer.FireCount22); Assert.Equal(1, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(1, analyzer.FireCount27); Assert.Equal(1, analyzer.FireCount28); Assert.Equal(1, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); } private class AnalyzerActions_01_Analyzer : DiagnosticAnalyzer { public int FireCount0; public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; public int FireCount18; public int FireCount19; public int FireCount20; public int FireCount21; public int FireCount22; public int FireCount23; public int FireCount24; public int FireCount25; public int FireCount26; public int FireCount27; public int FireCount28; public int FireCount29; public int FireCount30; public int FireCount31; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); } protected void Handle1(SyntaxNodeAnalysisContext context) { var literal = (LiteralExpressionSyntax)context.Node; switch (literal.ToString()) { case "0": Interlocked.Increment(ref FireCount0); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "1": Interlocked.Increment(ref FireCount1); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "2": Interlocked.Increment(ref FireCount2); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "3": Interlocked.Increment(ref FireCount3); Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); break; case "4": Interlocked.Increment(ref FireCount4); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "5": Interlocked.Increment(ref FireCount5); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(literal.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle2(SyntaxNodeAnalysisContext context) { var equalsValue = (EqualsValueClauseSyntax)context.Node; switch (equalsValue.ToString()) { case "= 0": Interlocked.Increment(ref FireCount15); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 1": Interlocked.Increment(ref FireCount16); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "= 4": Interlocked.Increment(ref FireCount6); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(equalsValue.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle3(SyntaxNodeAnalysisContext context) { var initializer = (ConstructorInitializerSyntax)context.Node; switch (initializer.ToString()) { case ": base(5)": Interlocked.Increment(ref FireCount7); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } Assert.Same(initializer.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle4(SyntaxNodeAnalysisContext context) { Interlocked.Increment(ref FireCount8); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); } protected void Handle5(SyntaxNodeAnalysisContext context) { var baseType = (PrimaryConstructorBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "A(2)": switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount9); break; case "B": Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } Assert.Same(baseType.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle6(SyntaxNodeAnalysisContext context) { var record = (RecordDeclarationSyntax)context.Node; switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount10); break; case "B": Interlocked.Increment(ref FireCount11); break; case "A": Interlocked.Increment(ref FireCount12); break; case "C": Interlocked.Increment(ref FireCount13); break; case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount14); break; default: Assert.True(false); break; } Assert.Same(record.SyntaxTree, context.ContainingSymbol!.DeclaringSyntaxReferences.Single().SyntaxTree); } protected void Handle7(SyntaxNodeAnalysisContext context) { var identifier = (IdentifierNameSyntax)context.Node; switch (identifier.Identifier.ValueText) { case "A": switch (identifier.Parent!.ToString()) { case "A(2)": Interlocked.Increment(ref FireCount18); Assert.Equal("B", context.ContainingSymbol.ToTestDisplayString()); break; case "A": Interlocked.Increment(ref FireCount19); Assert.Equal(SyntaxKind.SimpleBaseType, identifier.Parent.Kind()); Assert.Equal("C", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } break; case "Attr1": Interlocked.Increment(ref FireCount24); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr2": Interlocked.Increment(ref FireCount25); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "Attr3": Interlocked.Increment(ref FireCount26); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; } } protected void Handle8(SyntaxNodeAnalysisContext context) { var baseType = (SimpleBaseTypeSyntax)context.Node; switch (baseType.ToString()) { case "I1": switch (context.ContainingSymbol.ToTestDisplayString()) { case "A": Interlocked.Increment(ref FireCount20); break; case "B": Interlocked.Increment(ref FireCount21); break; case "C": Interlocked.Increment(ref FireCount22); break; default: Assert.True(false); break; } break; case "A": switch (context.ContainingSymbol.ToTestDisplayString()) { case "C": Interlocked.Increment(ref FireCount23); break; default: Assert.True(false); break; } break; case "System.Attribute": break; default: Assert.True(false); break; } } protected void Handle9(SyntaxNodeAnalysisContext context) { var parameterList = (ParameterListSyntax)context.Node; switch (parameterList.ToString()) { case "([Attr1]int X = 0)": Interlocked.Increment(ref FireCount27); Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr2]int Y = 1)": Interlocked.Increment(ref FireCount28); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "([Attr3]int Z = 4)": Interlocked.Increment(ref FireCount29); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; case "()": break; default: Assert.True(false); break; } } protected void Handle10(SyntaxNodeAnalysisContext context) { var argumentList = (ArgumentListSyntax)context.Node; switch (argumentList.ToString()) { case "(2)": Interlocked.Increment(ref FireCount30); Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); break; case "(5)": Interlocked.Increment(ref FireCount31); Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_02() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_02_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); } private class AnalyzerActions_02_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle, SymbolKind.Method); context.RegisterSymbolAction(Handle, SymbolKind.Property); context.RegisterSymbolAction(Handle, SymbolKind.Parameter); context.RegisterSymbolAction(Handle, SymbolKind.NamedType); } private void Handle(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount6); break; case "C": Interlocked.Increment(ref FireCount7); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_03() { var text1 = @" record A(int X = 0) {} record C { C(int Z = 4) {} } "; var analyzer = new AnalyzerActions_03_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(0, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(0, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); } private class AnalyzerActions_03_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolStartAction(Handle1, SymbolKind.Method); context.RegisterSymbolStartAction(Handle1, SymbolKind.Property); context.RegisterSymbolStartAction(Handle1, SymbolKind.Parameter); context.RegisterSymbolStartAction(Handle1, SymbolKind.NamedType); } private void Handle1(SymbolStartAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); context.RegisterSymbolEndAction(Handle2); break; case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount2); context.RegisterSymbolEndAction(Handle3); break; case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount3); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount4); context.RegisterSymbolEndAction(Handle4); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount5); break; case "A": Interlocked.Increment(ref FireCount9); Assert.Equal(0, FireCount1); Assert.Equal(0, FireCount2); Assert.Equal(0, FireCount6); Assert.Equal(0, FireCount7); context.RegisterSymbolEndAction(Handle5); break; case "C": Interlocked.Increment(ref FireCount10); Assert.Equal(0, FireCount4); Assert.Equal(0, FireCount8); context.RegisterSymbolEndAction(Handle6); break; case "System.Runtime.CompilerServices.IsExternalInit": break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { Assert.Equal("A..ctor([System.Int32 X = 0])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); } private void Handle3(SymbolAnalysisContext context) { Assert.Equal("System.Int32 A.X { get; init; }", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); } private void Handle4(SymbolAnalysisContext context) { Assert.Equal("C..ctor([System.Int32 Z = 4])", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); } private void Handle5(SymbolAnalysisContext context) { Assert.Equal("A", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); Assert.Equal(1, FireCount1); Assert.Equal(1, FireCount2); Assert.Equal(1, FireCount6); Assert.Equal(1, FireCount7); } private void Handle6(SymbolAnalysisContext context) { Assert.Equal("C", context.Symbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); Assert.Equal(1, FireCount4); Assert.Equal(1, FireCount8); } } [Fact] public void AnalyzerActions_04() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_04_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); } private class AnalyzerActions_04_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; public int FireCount10; public int FireCount11; public int FireCount12; public int FireCount13; public int FireCount14; public int FireCount15; public int FireCount16; public int FireCount17; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } protected void Handle1(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(SyntaxKind.RecordDeclaration, context.Operation.Syntax.Kind()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(SyntaxKind.ConstructorDeclaration, context.Operation.Syntax.Kind()); break; default: Assert.True(false); break; } } protected void Handle2(OperationAnalysisContext context) { switch (context.ContainingSymbol.ToTestDisplayString()) { case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount4); Assert.Equal(SyntaxKind.PrimaryConstructorBaseType, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: 'A(2)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: 'A(2)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '2') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount5); Assert.Equal(SyntaxKind.BaseConstructorInitializer, context.Operation.Syntax.Kind()); VerifyOperationTree((CSharpCompilation)context.Compilation, context.Operation, @" IInvocationOperation ( A..ctor([System.Int32 X = 0])) (OperationKind.Invocation, Type: System.Void) (Syntax: ': base(5)') Instance Receiver: IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: A, IsImplicit) (Syntax: ': base(5)') Arguments(1): IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: X) (OperationKind.Argument, Type: null) (Syntax: '5') ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5') InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null) "); break; default: Assert.True(false); break; } } protected void Handle3(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "100": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount6); break; case "0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount7); break; case "200": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount8); break; case "1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount9); break; case "2": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount10); break; case "300": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount11); break; case "4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount12); break; case "5": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount13); break; case "3": Assert.Equal("System.Int32 B.M()", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount17); break; default: Assert.True(false); break; } } protected void Handle4(OperationAnalysisContext context) { switch (context.Operation.Syntax.ToString()) { case "= 0": Assert.Equal("A..ctor([System.Int32 X = 0])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount14); break; case "= 1": Assert.Equal("B..ctor([System.Int32 Y = 1])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount15); break; case "= 4": Assert.Equal("C..ctor([System.Int32 Z = 4])", context.ContainingSymbol.ToTestDisplayString()); Interlocked.Increment(ref FireCount16); break; default: Assert.True(false); break; } } protected void Handle5(OperationAnalysisContext context) { Assert.True(false); } } [Fact] public void AnalyzerActions_05() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_05_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_05_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockAction(Handle); } private void Handle(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_06() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_06_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(0, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(1, analyzer.FireCount10); Assert.Equal(1, analyzer.FireCount11); Assert.Equal(1, analyzer.FireCount12); Assert.Equal(1, analyzer.FireCount13); Assert.Equal(1, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(1, analyzer.FireCount17); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_06_Analyzer : AnalyzerActions_04_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterOperationBlockStartAction(Handle); } private void Handle(OperationBlockStartAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount100); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount200); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount300); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount400); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); RegisterOperationAction(context); context.RegisterOperationBlockEndAction(Handle6); break; default: Assert.True(false); break; } } private void RegisterOperationAction(OperationBlockStartAnalysisContext context) { context.RegisterOperationAction(Handle1, OperationKind.ConstructorBody); context.RegisterOperationAction(Handle2, OperationKind.Invocation); context.RegisterOperationAction(Handle3, OperationKind.Literal); context.RegisterOperationAction(Handle4, OperationKind.ParameterInitializer); context.RegisterOperationAction(Handle5, OperationKind.PropertyInitializer); context.RegisterOperationAction(Handle5, OperationKind.FieldInitializer); } private void Handle6(OperationBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1000); Assert.Equal(2, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 0", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr1(100)", context.OperationBlocks[1].Syntax.ToString()); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2000); Assert.Equal(3, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 1", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr2(200)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[2].Kind); Assert.Equal("A(2)", context.OperationBlocks[2].Syntax.ToString()); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3000); Assert.Equal(4, context.OperationBlocks.Length); Assert.Equal(OperationKind.ParameterInitializer, context.OperationBlocks[0].Kind); Assert.Equal("= 4", context.OperationBlocks[0].Syntax.ToString()); Assert.Equal(OperationKind.None, context.OperationBlocks[1].Kind); Assert.Equal("Attr3(300)", context.OperationBlocks[1].Syntax.ToString()); Assert.Equal(OperationKind.Block, context.OperationBlocks[2].Kind); Assert.Equal(OperationKind.Invocation, context.OperationBlocks[3].Kind); Assert.Equal(": base(5)", context.OperationBlocks[3].Syntax.ToString()); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4000); Assert.Equal(1, context.OperationBlocks.Length); Assert.Equal(OperationKind.Block, context.OperationBlocks[0].Kind); break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_07() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_07_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); } private class AnalyzerActions_07_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockAction(Handle); } private void Handle(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_08() { var text1 = @" record A([Attr1]int X = 0) : I1 {} record B([Attr2]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_08_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount100); Assert.Equal(1, analyzer.FireCount200); Assert.Equal(1, analyzer.FireCount300); Assert.Equal(1, analyzer.FireCount400); Assert.Equal(1, analyzer.FireCount0); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(0, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); Assert.Equal(0, analyzer.FireCount10); Assert.Equal(0, analyzer.FireCount11); Assert.Equal(0, analyzer.FireCount12); Assert.Equal(0, analyzer.FireCount13); Assert.Equal(0, analyzer.FireCount14); Assert.Equal(1, analyzer.FireCount15); Assert.Equal(1, analyzer.FireCount16); Assert.Equal(0, analyzer.FireCount17); Assert.Equal(0, analyzer.FireCount18); Assert.Equal(0, analyzer.FireCount19); Assert.Equal(0, analyzer.FireCount20); Assert.Equal(0, analyzer.FireCount21); Assert.Equal(0, analyzer.FireCount22); Assert.Equal(0, analyzer.FireCount23); Assert.Equal(1, analyzer.FireCount24); Assert.Equal(1, analyzer.FireCount25); Assert.Equal(1, analyzer.FireCount26); Assert.Equal(0, analyzer.FireCount27); Assert.Equal(0, analyzer.FireCount28); Assert.Equal(0, analyzer.FireCount29); Assert.Equal(1, analyzer.FireCount30); Assert.Equal(1, analyzer.FireCount31); Assert.Equal(1, analyzer.FireCount1000); Assert.Equal(1, analyzer.FireCount2000); Assert.Equal(1, analyzer.FireCount3000); Assert.Equal(1, analyzer.FireCount4000); } private class AnalyzerActions_08_Analyzer : AnalyzerActions_01_Analyzer { public int FireCount100; public int FireCount200; public int FireCount300; public int FireCount400; public int FireCount1000; public int FireCount2000; public int FireCount3000; public int FireCount4000; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterCodeBlockStartAction<SyntaxKind>(Handle); } private void Handle(CodeBlockStartAnalysisContext<SyntaxKind> context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount100); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount200); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount300); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount400); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } context.RegisterSyntaxNodeAction(Handle1, SyntaxKind.NumericLiteralExpression); context.RegisterSyntaxNodeAction(Handle2, SyntaxKind.EqualsValueClause); context.RegisterSyntaxNodeAction(Handle3, SyntaxKind.BaseConstructorInitializer); context.RegisterSyntaxNodeAction(Handle4, SyntaxKind.ConstructorDeclaration); context.RegisterSyntaxNodeAction(Handle5, SyntaxKind.PrimaryConstructorBaseType); context.RegisterSyntaxNodeAction(Handle6, SyntaxKind.RecordDeclaration); context.RegisterSyntaxNodeAction(Handle7, SyntaxKind.IdentifierName); context.RegisterSyntaxNodeAction(Handle8, SyntaxKind.SimpleBaseType); context.RegisterSyntaxNodeAction(Handle9, SyntaxKind.ParameterList); context.RegisterSyntaxNodeAction(Handle10, SyntaxKind.ArgumentList); context.RegisterCodeBlockEndAction(Handle11); } private void Handle11(CodeBlockAnalysisContext context) { switch (context.OwningSymbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "A" } }: Interlocked.Increment(ref FireCount1000); break; default: Assert.True(false); break; } break; case "B..ctor([System.Int32 Y = 1])": switch (context.CodeBlock) { case RecordDeclarationSyntax { Identifier: { ValueText: "B" } }: Interlocked.Increment(ref FireCount2000); break; default: Assert.True(false); break; } break; case "C..ctor([System.Int32 Z = 4])": switch (context.CodeBlock) { case ConstructorDeclarationSyntax { Identifier: { ValueText: "C" } }: Interlocked.Increment(ref FireCount3000); break; default: Assert.True(false); break; } break; case "System.Int32 B.M()": switch (context.CodeBlock) { case MethodDeclarationSyntax { Identifier: { ValueText: "M" } }: Interlocked.Increment(ref FireCount4000); break; default: Assert.True(false); break; } break; default: Assert.True(false); break; } } } [Fact] public void AnalyzerActions_09() { var text1 = @" record A([Attr1(100)]int X = 0) : I1 {} record B([Attr2(200)]int Y = 1) : A(2), I1 { int M() => 3; } record C : A, I1 { C([Attr3(300)]int Z = 4) : base(5) {} } interface I1 {} "; var analyzer = new AnalyzerActions_09_Analyzer(); var comp = CreateCompilation(text1); comp.GetAnalyzerDiagnostics(new[] { analyzer }, null).Verify(); Assert.Equal(1, analyzer.FireCount1); Assert.Equal(1, analyzer.FireCount2); Assert.Equal(1, analyzer.FireCount3); Assert.Equal(1, analyzer.FireCount4); Assert.Equal(1, analyzer.FireCount5); Assert.Equal(1, analyzer.FireCount6); Assert.Equal(1, analyzer.FireCount7); Assert.Equal(1, analyzer.FireCount8); Assert.Equal(1, analyzer.FireCount9); } private class AnalyzerActions_09_Analyzer : DiagnosticAnalyzer { public int FireCount1; public int FireCount2; public int FireCount3; public int FireCount4; public int FireCount5; public int FireCount6; public int FireCount7; public int FireCount8; public int FireCount9; private static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor("XY0000", "Test", "Test", "Test", DiagnosticSeverity.Warning, true, "Test", "Test"); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(Handle1, SymbolKind.Method); context.RegisterSymbolAction(Handle2, SymbolKind.Property); context.RegisterSymbolAction(Handle3, SymbolKind.Parameter); } private void Handle1(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "A..ctor([System.Int32 X = 0])": Interlocked.Increment(ref FireCount1); break; case "B..ctor([System.Int32 Y = 1])": Interlocked.Increment(ref FireCount2); break; case "C..ctor([System.Int32 Z = 4])": Interlocked.Increment(ref FireCount3); break; case "System.Int32 B.M()": Interlocked.Increment(ref FireCount4); break; default: Assert.True(false); break; } } private void Handle2(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "System.Int32 A.X { get; init; }": Interlocked.Increment(ref FireCount5); break; case "System.Int32 B.Y { get; init; }": Interlocked.Increment(ref FireCount6); break; default: Assert.True(false); break; } } private void Handle3(SymbolAnalysisContext context) { switch (context.Symbol.ToTestDisplayString()) { case "[System.Int32 X = 0]": Interlocked.Increment(ref FireCount7); break; case "[System.Int32 Y = 1]": Interlocked.Increment(ref FireCount8); break; case "[System.Int32 Z = 4]": Interlocked.Increment(ref FireCount9); break; default: Assert.True(false); break; } } } [Fact] [WorkItem(46657, "https://github.com/dotnet/roslyn/issues/46657")] public void CanDeclareIteratorInRecord() { var source = @" using System.Collections.Generic; public record X(int a) { public static void Main() { foreach(var i in new X(42).GetItems()) { System.Console.Write(i); } } public IEnumerable<int> GetItems() { yield return a; yield return a + 1; } }"; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe, parseOptions: TestOptions.Regular9) .VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "4243", verify: Verification.Skipped /* init-only */); } [Fact] public void DefaultCtor_01() { var src = @" record C { } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_02() { var src = @" record B(int x); record C : B { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_03() { var src = @" record C { public C(C c){} } class Program { static void Main() { var x = new C(); var y = new C(); System.Console.WriteLine(x == y); } } "; var verifier = CompileAndVerify(src, expectedOutput: "True"); verifier.VerifyDiagnostics(); verifier.VerifyIL("C..ctor()", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""object..ctor()"" IL_0006: ret } "); } [Fact] public void DefaultCtor_04() { var src = @" record B(int x); record C : B { public C(C c) : base(c) {} } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,8): error CS1729: 'B' does not contain a constructor that takes 0 arguments // record C : B Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("B", "0").WithLocation(4, 8) ); } [Fact] public void DefaultCtor_05() { var src = @" record C(int x); class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (8,17): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.C(int)' // _ = new C(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("x", "C.C(int)").WithLocation(8, 17) ); } [Fact] public void DefaultCtor_06() { var src = @" record C { C(int x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] public void DefaultCtor_07() { var src = @" class C { C(C x) {} } class Program { static void Main() { _ = new C(); } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (11,17): error CS1729: 'C' does not contain a constructor that takes 0 arguments // _ = new C(); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "0").WithLocation(11, 17) ); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_RecordWithStaticMembers() { var src = @" var c1 = new C1(42); System.Console.Write(c1.ToString()); record C1(int I1) { public static int field1 = 44; public const int field2 = 44; public static int P1 { set { } } public static int P2 { get { return 1; } set { } } public static int P3 { get { return 1; } } } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] [WorkItem(47867, "https://github.com/dotnet/roslyn/issues/47867")] public void ToString_NestedRecord() { var src = @" var c1 = new Outer.C1(42); System.Console.Write(c1.ToString()); public class Outer { public record C1(int I1); } "; var compDebug = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); var compRelease = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.ReleaseExe); CompileAndVerify(compDebug, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compDebug.VerifyEmitDiagnostics(); CompileAndVerify(compRelease, expectedOutput: "C1 { I1 = 42 }", verify: Verification.Skipped /* init-only */); compRelease.VerifyEmitDiagnostics(); } [Fact] public void ToString_Cycle_01() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public Rec Inner; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_02() { var src = @" using System; var rec = new Rec(); rec.Inner = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Base { public Rec Inner; } public record Rec : Base { } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_03() { var src = @" using System; var rec = new Rec(); rec.RecStruct.Rec = rec; try { rec.ToString(); } catch (Exception ex) { Console.Write(ex.GetType().FullName); } public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; CompileAndVerify(src, expectedOutput: "System.InsufficientExecutionStackException"); } [Fact] public void ToString_Cycle_04() { var src = @" public record Rec { public RecStruct RecStruct; } public record struct RecStruct { public Rec Rec; } "; var comp = CreateCompilation(src); var verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: call ""void System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()"" IL_0005: ldarg.1 IL_0006: ldstr ""RecStruct = "" IL_000b: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0010: pop IL_0011: ldarg.1 IL_0012: ldarg.0 IL_0013: ldflda ""RecStruct Rec.RecStruct"" IL_0018: constrained. ""RecStruct"" IL_001e: callvirt ""string object.ToString()"" IL_0023: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0028: pop IL_0029: ldc.i4.1 IL_002a: ret }"); comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__EnsureSufficientExecutionStack); verifier = CompileAndVerify(comp); verifier.VerifyDiagnostics(); verifier.VerifyIL("Rec.PrintMembers", @" { // Code size 38 (0x26) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldstr ""RecStruct = "" IL_0006: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_000b: pop IL_000c: ldarg.1 IL_000d: ldarg.0 IL_000e: ldflda ""RecStruct Rec.RecStruct"" IL_0013: constrained. ""RecStruct"" IL_0019: callvirt ""string object.ToString()"" IL_001e: callvirt ""System.Text.StringBuilder System.Text.StringBuilder.Append(string)"" IL_0023: pop IL_0024: ldc.i4.1 IL_0025: ret }"); } [Fact] [WorkItem(50040, "https://github.com/dotnet/roslyn/issues/50040")] public void RaceConditionInAddMembers() { var src = @" #nullable enable using System; using System.Linq.Expressions; using System.Threading.Tasks; var collection = new Collection<Hamster>(); Hamster h = null!; await collection.MethodAsync(entity => entity.Name! == ""bar"", h); public record Collection<T> where T : Document { public Task MethodAsync<TDerived>(Expression<Func<TDerived, bool>> filter, TDerived td) where TDerived : T => throw new NotImplementedException(); public Task MethodAsync<TDerived2>(Task<TDerived2> filterDefinition, TDerived2 td) where TDerived2 : T => throw new NotImplementedException(); } public sealed record HamsterCollection : Collection<Hamster> { } public abstract class Document { } public sealed class Hamster : Document { public string? Name { get; private set; } } "; for (int i = 0; i < 100; i++) { var comp = CreateCompilation(new[] { src, IsExternalInitTypeDefinition }, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); } } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact, WorkItem(53912, "https://github.com/dotnet/roslyn/issues/53912")] public void XmlDoc_CrefToPositionalProperty_Test53912() { var source = @" namespace NamespaceA { /// <summary> /// A sample record type /// </summary> /// <param name=""Prop1""> /// A property /// </param> public record LinkDestinationRecord(string Prop1); /// <summary> /// Simple class. /// </summary> public class LinkingClass { /// <inheritdoc cref=""LinkDestinationRecord.Prop1"" /> public string Prop1A { get; init; } } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, assemblyName: "Test"); var actual = GetDocumentationCommentText(comp); // the cref becomes `P:...` var expected = (@"<?xml version=""1.0""?> <doc> <assembly> <name>Test</name> </assembly> <members> <member name=""T:NamespaceA.LinkDestinationRecord""> <summary> A sample record type </summary> <param name=""Prop1""> A property </param> </member> <member name=""M:NamespaceA.LinkDestinationRecord.#ctor(System.String)""> <summary> A sample record type </summary> <param name=""Prop1""> A property </param> </member> <member name=""T:NamespaceA.LinkingClass""> <summary> Simple class. </summary> </member> <member name=""P:NamespaceA.LinkingClass.Prop1A""> <inheritdoc cref=""P:NamespaceA.LinkDestinationRecord.Prop1"" /> </member> </members> </doc>"); Assert.Equal(expected, actual); } [Fact] public void XmlDoc_RecordClass() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record class C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Cref() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for <see cref=""I1""/></param> public record C(int I1) { /// <summary>Summary</summary> /// <param name=""x"">Description for <see cref=""x""/></param> public void M(int x) { } } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,52): warning CS1574: XML comment has cref attribute 'x' that could not be resolved // /// <param name="x">Description for <see cref="x"/></param> Diagnostic(ErrorCode.WRN_BadXMLRef, "x").WithArguments("x").WithLocation(7, 52) ); var tree = comp.SyntaxTrees.Single(); var docComments = tree.GetCompilationUnitRoot().DescendantTrivia().Select(trivia => trivia.GetStructure()).OfType<DocumentationCommentTriviaSyntax>(); var cref = docComments.First().DescendantNodes().OfType<XmlCrefAttributeSyntax>().First().Cref; Assert.Equal("I1", cref.ToString()); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal(SymbolKind.Property, model.GetSymbolInfo(cref).Symbol!.Kind); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Error() { var src = @" /// <summary>Summary</summary> /// <param name=""Error""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18), // (3,18): warning CS1572: XML comment has a param tag for 'Error', but there is no parameter by that name // /// <param name="Error"></param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "Error").WithArguments("Error").WithLocation(3, 18) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Duplicate() { var src = @" /// <summary>Summary</summary> /// <param name=""I1""></param> /// <param name=""I1""></param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12), // (4,12): warning CS1571: XML comment has a duplicate param tag for 'I1' // /// <param name="I1"></param> Diagnostic(ErrorCode.WRN_DuplicateParamTag, @"name=""I1""").WithArguments("I1").WithLocation(4, 12) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef() { var src = @" /// <summary>Summary <paramref name=""I1""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary <paramref name=""I1""/></summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_ParamRef_Error() { var src = @" /// <summary>Summary <paramref name=""Error""/></summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,38): warning CS1734: XML comment on 'C' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C").WithLocation(2, 38), // (2,38): warning CS1734: XML comment on 'C.C(int)' has a paramref tag for 'Error', but there is no parameter by that name // /// <summary>Summary <paramref name="Error"/></summary> Diagnostic(ErrorCode.WRN_UnmatchedParamRefTag, "Error").WithArguments("Error", "C.C(int)").WithLocation(2, 38) ); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_WithExplicitProperty() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1) { /// <summary>Property summary</summary> public int I1 { get; init; } = I1; } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal( @"<member name=""P:C.I1""> <summary>Property summary</summary> </member> ", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_EmptyParameterList() { var src = @" /// <summary>Summary</summary> public record C(); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<MethodSymbol>().Where(m => m.Parameters.IsEmpty).Single(); Assert.Equal( @"<member name=""M:C.#ctor""> <summary>Summary</summary> </member> ", constructor.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond() { var src = @" public partial record C; /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListFirst_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_ParamListSecond_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record E; public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (3,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(3, 18), // (6,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(6, 23) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocSecond() { var src = @" public partial record C(int I1); /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record C(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'C.C(int)' // public partial record C(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "C").WithArguments("C.C(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record C(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var c = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal( @"<member name=""T:C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", c.GetDocumentationCommentXml()); var cConstructor = c.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, cConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", cConstructor.GetDocumentationCommentXml()); Assert.Equal("", cConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", c.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocFirst() { var src = @" /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public partial record D(int I1); public partial record D(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record D(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(6, 24) ); var d = comp.GetMember<NamedTypeSymbol>("D"); Assert.Equal( @"<member name=""T:D""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", d.GetDocumentationCommentXml()); var dConstructor = d.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:D.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", dConstructor.GetDocumentationCommentXml()); Assert.Equal("", dConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", d.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DuplicateParameterList_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""I1"">Description2 for I1</param> public partial record E(int I1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'I1', but there is no parameter by that name // /// <param name="I1">Description2 for I1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "I1").WithArguments("I1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(int I1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(int I1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""I1"">Description2 for I1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocSecond() { var src = @" public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (2,23): warning CS1591: Missing XML comment for publicly visible type or member 'E.E(int)' // public partial record E(int I1); Diagnostic(ErrorCode.WRN_MissingXMLComment, "E").WithArguments("E.E(int)").WithLocation(2, 23), // (5,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(5, 18), // (6,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(6, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal("", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Partial_DifferentParameterLists_XmlDocOnBoth() { var src = @" /// <summary>Summary1</summary> /// <param name=""I1"">Description1 for I1</param> public partial record E(int I1); /// <summary>Summary2</summary> /// <param name=""S1"">Description2 for S1</param> public partial record E(string S1); namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (7,18): warning CS1572: XML comment has a param tag for 'S1', but there is no parameter by that name // /// <param name="S1">Description2 for S1</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "S1").WithArguments("S1").WithLocation(7, 18), // (8,24): error CS8863: Only a single record partial declaration may have a parameter list // public partial record E(string S1); Diagnostic(ErrorCode.ERR_MultipleRecordParameterLists, "(string S1)").WithLocation(8, 24) ); var e = comp.GetMember<NamedTypeSymbol>("E"); Assert.Equal( @"<member name=""T:E""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> <summary>Summary2</summary> <param name=""S1"">Description2 for S1</param> </member> ", e.GetDocumentationCommentXml()); var eConstructor = e.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal(1, eConstructor.DeclaringSyntaxReferences.Count()); Assert.Equal( @"<member name=""M:E.#ctor(System.Int32)""> <summary>Summary1</summary> <param name=""I1"">Description1 for I1</param> </member> ", eConstructor.GetDocumentationCommentXml()); Assert.Equal("", eConstructor.GetParameters()[0].GetDocumentationCommentXml()); Assert.Equal("", e.GetMembers("I1").Single().GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested() { var src = @" /// <summary>Summary</summary> public class Outer { /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics(); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); Assert.Equal( @"<member name=""T:Outer.C""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", cMember.GetDocumentationCommentXml()); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> </member> ", constructor.GetDocumentationCommentXml()); Assert.Equal("", constructor.GetParameters()[0].GetDocumentationCommentXml()); var property = cMember.GetMembers("I1").Single(); Assert.Equal("", property.GetDocumentationCommentXml()); } [Fact] [WorkItem(44571, "https://github.com/dotnet/roslyn/issues/44571")] public void XmlDoc_Nested_ReferencingOuterParam() { var src = @" /// <summary>Summary</summary> /// <param name=""O1"">Description for O1</param> public record Outer(object O1) { /// <summary>Summary</summary> public int P1 { get; set; } /// <summary>Summary</summary> /// <param name=""I1"">Description for I1</param> /// <param name=""O1"">Error O1</param> /// <param name=""P1"">Error P1</param> /// <param name=""C"">Error C</param> public record C(int I1); } namespace System.Runtime.CompilerServices { /// <summary>Ignored</summary> public static class IsExternalInit { } } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularWithDocumentationComments); comp.VerifyDiagnostics( // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (11,22): warning CS1572: XML comment has a param tag for 'O1', but there is no parameter by that name // /// <param name="O1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "O1").WithArguments("O1").WithLocation(11, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (12,22): warning CS1572: XML comment has a param tag for 'P1', but there is no parameter by that name // /// <param name="P1">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "P1").WithArguments("P1").WithLocation(12, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22), // (13,22): warning CS1572: XML comment has a param tag for 'C', but there is no parameter by that name // /// <param name="C">Error</param> Diagnostic(ErrorCode.WRN_UnmatchedParamTag, "C").WithArguments("C").WithLocation(13, 22) ); var cMember = comp.GetMember<NamedTypeSymbol>("Outer.C"); var constructor = cMember.GetMembers(".ctor").OfType<SynthesizedRecordConstructor>().Single(); Assert.Equal( @"<member name=""M:Outer.C.#ctor(System.Int32)""> <summary>Summary</summary> <param name=""I1"">Description for I1</param> <param name=""O1"">Error O1</param> <param name=""P1"">Error P1</param> <param name=""C"">Error C</param> </member> ", constructor.GetDocumentationCommentXml()); } [Fact, WorkItem(51590, "https://github.com/dotnet/roslyn/issues/51590")] public void SealedIncomplete() { var source = @" public sealed record("; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,21): error CS1001: Identifier expected // public sealed record( Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(2, 21), // (2,22): error CS1026: ) expected // public sealed record( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(2, 22), // (2,22): error CS1514: { expected // public sealed record( Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(2, 22), // (2,22): error CS1513: } expected // public sealed record( Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(2, 22) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } // hiding } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } // hiding Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Field_HiddenWithConstant() { var source = @" public record Base { public int I = 0; public Base(int ignored) { } } public record C(int I) : Base(I) { public const int I = 0; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,22): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const int I = 0; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 22) ); } [Fact] public void FieldAsPositionalMember() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (8,10): error CS8773: Feature 'positional fields in records' is not available in C# 9.0. Please use language version 10.0 or greater. // record A(int X) Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "int X").WithArguments("positional fields in records", "10.0").WithLocation(8, 10) ); comp = CreateCompilation(source, parseOptions: TestOptions.Regular10); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_TwoParameters() { var source = @" var a = new A(42, 43); System.Console.Write(a.Y); System.Console.Write("" - ""); a.Deconstruct(out int x, out int y); System.Console.Write(y); record A(int X, int Y) { public int X = X; public int Y = Y; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "43 - 43"); verifier.VerifyIL("A.Deconstruct", @" { // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ldarg.2 IL_0009: ldarg.0 IL_000a: ldfld ""int A.Y"" IL_000f: stind.i4 IL_0010: ret } "); } [Fact] public void FieldAsPositionalMember_Readonly() { var source = @" var a = new A(42); System.Console.Write(a.X); System.Console.Write("" - ""); a.Deconstruct(out int x); System.Console.Write(x); record A(int X) { public readonly int X = X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42 - 42", verify: Verification.Skipped /* init-only */); verifier.VerifyIL("A.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int A.X"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_UnusedParameter() { var source = @" record A(int X) { public int X; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): warning CS8907: Parameter 'X' is unread. Did you forget to use it to initialize the property with that name? // record A(int X) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "X").WithArguments("X").WithLocation(2, 14), // (4,16): warning CS0649: Field 'A.X' is never assigned to, and will always have its default value 0 // public int X; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "X").WithArguments("A.X", "0").WithLocation(4, 16) ); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 0; } public record C(int I) : Base { public int I = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int C.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_CurrentTypeComesFirst_FieldInBase() { var source = @" var c = new C(42); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 0; } public record C(int I) : Base { public int I { get; set; } = I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (12,16): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I { get; set; } = I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(12, 16) ); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int C.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: ldfld ""int Base.I"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact] public void FieldAsPositionalMember_FieldFromBase_StaticFieldInDerivedType() { var source = @" public record Base { public int I = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I = 42; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public static int I { get; set; } = 42; } "; comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,23): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public static int I { get; set; } = 42; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 23) ); } [Fact] public void FieldAsPositionalMember_Static() { var source = @" record A(int X) { public static int X = 0; public int Y = X; } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'A.X' must be a readable instance property or field of type 'int' to match positional parameter 'X'. // record A(int X) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "X").WithArguments("A.X", "int", "X").WithLocation(2, 14) ); } [Fact] public void FieldAsPositionalMember_Const() { var src = @" record C(int P) { const int P = 4; } record C2(int P) { const int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14), // (2,14): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(2, 14), // (6,15): error CS8866: Record member 'C2.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C2(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C2.P", "int", "P").WithLocation(6, 15), // (6,15): warning CS8907: Parameter 'P' is unread. Did you forget to use it to initialize the property with that name? // record C2(int P) Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "P").WithArguments("P").WithLocation(6, 15), // (8,15): error CS0110: The evaluation of the constant value for 'C2.P' involves a circular definition // const int P = P; Diagnostic(ErrorCode.ERR_CircConstValue, "P").WithArguments("C2.P").WithLocation(8, 15) ); } [Fact] public void FieldAsPositionalMember_Volatile() { var src = @" record C(int P) { public volatile int P = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_DifferentAccessibility() { var src = @" record C(int P) { private int P = P; } record C2(int P) { protected int P = P; } record C3(int P) { internal int P = P; } "; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); } [Fact] public void FieldAsPositionalMember_WrongType() { var src = @" record C(int P) { public string P = null; public int Q = P; }"; var comp = CreateCompilation(src, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (2,14): error CS8866: Record member 'C.P' must be a readable instance property or field of type 'int' to match positional parameter 'P'. // record C(int P) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "P").WithArguments("C.P", "int", "P").WithLocation(2, 14) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_DeconstructInSource() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } public void Deconstruct(out int i) { i = 0; } } "; var expected = new[] { // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,17): warning CS0108: 'C.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "Base.I").WithLocation(9, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithZeroArityMethod_WithNew() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) // 1 { public new void I() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) // 1 Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithGenericMethod() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public void I<T>() { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (11,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(11, 21), // (13,17): warning CS0108: 'C.I<T>()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public void I<T>() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I<T>()", "Base.I").WithLocation(13, 17) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_FromGrandBase() { var source = @" public record GrandBase { public int I { get; set; } = 42; } public record Base : GrandBase { public Base(int ignored) { } } public record C(int I) : Base(I) { public void I() { } } "; var expected = new[] { // (10,21): error CS8913: The positional member 'GrandBase.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("GrandBase.I").WithLocation(10, 21), // (12,17): warning CS0108: 'C.I()' hides inherited member 'GrandBase.I'. Use the new keyword if hiding was intended. // public void I() { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I()", "GrandBase.I").WithLocation(12, 17) }; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(expected); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int Item { get; set; } = 42; public Base(int ignored) { } } public record C(int Item) : Base(Item) { public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.Item.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_NotHiddenByIndexer_WithIndexerName() { var source = @" var c = new C(0); c.Deconstruct(out int i); System.Console.Write(i); public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { [System.Runtime.CompilerServices.IndexerName(""I"")] public int this[int x] { get => throw null; } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics(); var verifier = CompileAndVerify(comp, expectedOutput: "42"); verifier.VerifyIL("C.Deconstruct", @" { // Code size 9 (0x9) .maxstack 2 IL_0000: ldarg.1 IL_0001: ldarg.0 IL_0002: call ""int Base.I.get"" IL_0007: stind.i4 IL_0008: ret } "); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithType() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public class I { } } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,18): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public class I { } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 18) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithEvent() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public event System.Action I; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8913: The positional member 'Base.I' found corresponding to this parameter is hidden. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_HiddenPositionalMember, "I").WithArguments("Base.I").WithLocation(7, 21), // (9,32): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public event System.Action I; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 32), // (9,32): warning CS0067: The event 'C.I' is never used // public event System.Action I; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "I").WithArguments("C.I").WithLocation(9, 32) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_HiddenWithConstant() { var source = @" public record Base { public int I { get; set; } = 42; public Base(int ignored) { } } public record C(int I) : Base(I) { public const string I = null; } "; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (7,21): error CS8866: Record member 'C.I' must be a readable instance property or field of type 'int' to match positional parameter 'I'. // public record C(int I) : Base(I) Diagnostic(ErrorCode.ERR_BadRecordMemberForPositionalParameter, "I").WithArguments("C.I", "int", "I").WithLocation(7, 21), // (9,25): warning CS0108: 'C.I' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public const string I = null; Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("C.I", "Base.I").WithLocation(9, 25) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase() { var source = @" abstract record Base { public abstract int I { get; init; } } record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): warning CS0108: 'Derived.I()' hides inherited member 'Base.I'. Use the new keyword if hiding was intended. // public int I() { return 0; } Diagnostic(ErrorCode.WRN_NewRequired, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact, WorkItem(52630, "https://github.com/dotnet/roslyn/issues/52630")] public void HiddenPositionalMember_Property_AbstractInBase_AbstractInDerived() { var source = @" abstract record Base { public abstract int I { get; init; } } abstract record Derived(int I) : Base { public int I() { return 0; } } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.RegularPreview); comp.VerifyEmitDiagnostics( // (8,16): error CS0533: 'Derived.I()' hides inherited abstract member 'Base.I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "I").WithArguments("Derived.I()", "Base.I").WithLocation(8, 16), // (8,16): error CS0102: The type 'Derived' already contains a definition for 'I' // public int I() { return 0; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("Derived", "I").WithLocation(8, 16) ); } [Fact] public void InterfaceWithParameters() { var src = @" public interface I { } record R(int X) : I() { } record R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,20): error CS8861: Unexpected argument list. // record R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 20), // (10,21): error CS8861: Unexpected argument list. // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 21), // (10,21): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 21) ); } [Fact] public void InterfaceWithParameters_RecordClass() { var src = @" public interface I { } record class R(int X) : I() { } record class R2(int X) : I(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,26): error CS8861: Unexpected argument list. // record class R(int X) : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 26), // (10,27): error CS8861: Unexpected argument list. // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(X)").WithLocation(10, 27), // (10,27): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record class R2(int X) : I(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(10, 27) ); } [Fact] public void BaseErrorTypeWithParameters() { var src = @" record R2(int X) : Error(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,8): error CS0115: 'R2.ToString()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.ToString()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.EqualityContract': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.EqualityContract").WithLocation(2, 8), // (2,8): error CS0115: 'R2.Equals(object?)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.Equals(object?)").WithLocation(2, 8), // (2,8): error CS0115: 'R2.GetHashCode()': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.GetHashCode()").WithLocation(2, 8), // (2,8): error CS0115: 'R2.PrintMembers(StringBuilder)': no suitable method found to override // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "R2").WithArguments("R2.PrintMembers(System.Text.StringBuilder)").WithLocation(2, 8), // (2,20): error CS0246: The type or namespace name 'Error' could not be found (are you missing a using directive or an assembly reference?) // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Error").WithArguments("Error").WithLocation(2, 20), // (2,25): error CS1729: 'Error' does not contain a constructor that takes 1 arguments // record R2(int X) : Error(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("Error", "1").WithLocation(2, 25) ); } [Fact] public void BaseDynamicTypeWithParameters() { var src = @" record R(int X) : dynamic(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS1965: 'R': cannot derive from the dynamic type // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("R").WithLocation(2, 19), // (2,26): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : dynamic(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 26) ); } [Fact] public void BaseTypeParameterTypeWithParameters() { var src = @" class C<T> { record R(int X) : T(X) { } } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (4,23): error CS0689: Cannot derive from 'T' because it is a type parameter // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_DerivingFromATyVar, "T").WithArguments("T").WithLocation(4, 23), // (4,24): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : T(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(4, 24) ); } [Fact] public void BaseObjectTypeWithParameters() { var src = @" record R(int X) : object(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,25): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : object(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 25) ); } [Fact] public void BaseValueTypeTypeWithParameters() { var src = @" record R(int X) : System.ValueType(X) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (2,19): error CS0644: 'R' cannot derive from special class 'ValueType' // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "System.ValueType").WithArguments("R", "System.ValueType").WithLocation(2, 19), // (2,35): error CS1729: 'object' does not contain a constructor that takes 1 arguments // record R(int X) : System.ValueType(X) Diagnostic(ErrorCode.ERR_BadCtorArgCount, "(X)").WithArguments("object", "1").WithLocation(2, 35) ); } [Fact] public void InterfaceWithParameters_NoPrimaryConstructor() { var src = @" public interface I { } record R : I() { } record R2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,13): error CS8861: Unexpected argument list. // record R : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 13), // (10,14): error CS8861: Unexpected argument list. // record R2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 14) ); } [Fact] public void InterfaceWithParameters_Class() { var src = @" public interface I { } class C : I() { } class C2 : I(0) { } "; var comp = CreateCompilation(src); comp.VerifyEmitDiagnostics( // (6,12): error CS8861: Unexpected argument list. // class C : I() Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "()").WithLocation(6, 12), // (10,13): error CS8861: Unexpected argument list. // class C2 : I(0) Diagnostic(ErrorCode.ERR_UnexpectedArgumentList, "(0)").WithLocation(10, 13) ); } [Theory, WorkItem(44902, "https://github.com/dotnet/roslyn/issues/44902")] [CombinatorialData] public void CrossAssemblySupportingAndNotSupportingCovariantReturns(bool useCompilationReference) { var sourceA = @"public record B(int I) { } public record C(int I) : B(I);"; var compA = CreateEmptyCompilation(new[] { sourceA, IsExternalInitTypeDefinition }, references: TargetFrameworkUtil.GetReferences(TargetFramework.NetStandard20)); compA.VerifyDiagnostics(); Assert.False(compA.Assembly.RuntimeSupportsCovariantReturnsOfClasses); var actualMembers = compA.GetMember<NamedTypeSymbol>("C").GetMembers().ToTestDisplayStrings(); var expectedMembers = new[] { "C..ctor(System.Int32 I)", "System.Type C.EqualityContract.get", "System.Type C.EqualityContract { get; }", "System.String C.ToString()", "System.Boolean C." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean C.op_Inequality(C? left, C? right)", "System.Boolean C.op_Equality(C? left, C? right)", "System.Int32 C.GetHashCode()", "System.Boolean C.Equals(System.Object? obj)", "System.Boolean C.Equals(B? other)", "System.Boolean C.Equals(C? other)", "B C." + WellKnownMemberNames.CloneMethodName + "()", "C..ctor(C original)", "void C.Deconstruct(out System.Int32 I)", }; AssertEx.Equal(expectedMembers, actualMembers); var refA = useCompilationReference ? compA.ToMetadataReference() : compA.EmitToImageReference(); var sourceB = "record D(int I) : C(I);"; // CS1701: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy var compB = CreateCompilation(sourceB, references: new[] { refA }, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions("CS1701", ReportDiagnostic.Suppress), parseOptions: TestOptions.Regular9, targetFramework: TargetFramework.NetCoreApp); compB.VerifyDiagnostics(); Assert.True(compB.Assembly.RuntimeSupportsCovariantReturnsOfClasses); actualMembers = compB.GetMember<NamedTypeSymbol>("D").GetMembers().ToTestDisplayStrings(); expectedMembers = new[] { "D..ctor(System.Int32 I)", "System.Type D.EqualityContract.get", "System.Type D.EqualityContract { get; }", "System.String D.ToString()", "System.Boolean D." + WellKnownMemberNames.PrintMembersMethodName + "(System.Text.StringBuilder builder)", "System.Boolean D.op_Inequality(D? left, D? right)", "System.Boolean D.op_Equality(D? left, D? right)", "System.Int32 D.GetHashCode()", "System.Boolean D.Equals(System.Object? obj)", "System.Boolean D.Equals(C? other)", "System.Boolean D.Equals(D? other)", "D D." + WellKnownMemberNames.CloneMethodName + "()", "D..ctor(D original)", "void D.Deconstruct(out System.Int32 I)" }; AssertEx.Equal(expectedMembers, actualMembers); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Tools/ExternalAccess/FSharp/SignatureHelp/FSharpSignatureHelpParameter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.SignatureHelp { internal class FSharpSignatureHelpParameter { /// <summary> /// The name of this parameter. /// </summary> public string Name { get; } /// <summary> /// Documentation for this parameter. This should normally be presented to the user when /// this parameter is selected. /// </summary> public Func<CancellationToken, IEnumerable<TaggedText>> DocumentationFactory { get; } /// <summary> /// Display parts to show before the normal display parts for the parameter. /// </summary> public IList<TaggedText> PrefixDisplayParts { get; } /// <summary> /// Display parts to show after the normal display parts for the parameter. /// </summary> public IList<TaggedText> SuffixDisplayParts { get; } /// <summary> /// Display parts for this parameter. This should normally be presented to the user as part /// of the entire signature display. /// </summary> public IList<TaggedText> DisplayParts { get; } /// <summary> /// True if this parameter is optional or not. Optional parameters may be presented in a /// different manner to users. /// </summary> public bool IsOptional { get; } /// <summary> /// Display parts for this parameter that should be presented to the user when this /// parameter is selected. /// </summary> public IList<TaggedText> SelectedDisplayParts { get; } private static readonly Func<CancellationToken, IEnumerable<TaggedText>> s_emptyDocumentationFactory = _ => SpecializedCollections.EmptyEnumerable<TaggedText>(); public FSharpSignatureHelpParameter( string name, bool isOptional, Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory, IEnumerable<TaggedText> displayParts, IEnumerable<TaggedText> prefixDisplayParts = null, IEnumerable<TaggedText> suffixDisplayParts = null, IEnumerable<TaggedText> selectedDisplayParts = null) { this.Name = name ?? string.Empty; this.IsOptional = isOptional; this.DocumentationFactory = documentationFactory ?? s_emptyDocumentationFactory; this.DisplayParts = displayParts.ToImmutableArrayOrEmpty(); this.PrefixDisplayParts = prefixDisplayParts.ToImmutableArrayOrEmpty(); this.SuffixDisplayParts = suffixDisplayParts.ToImmutableArrayOrEmpty(); this.SelectedDisplayParts = selectedDisplayParts.ToImmutableArrayOrEmpty(); } internal IEnumerable<TaggedText> GetAllParts() { return this.PrefixDisplayParts.Concat(this.DisplayParts) .Concat(this.SuffixDisplayParts) .Concat(this.SelectedDisplayParts); } public override string ToString() { var prefix = string.Concat(PrefixDisplayParts); var display = string.Concat(DisplayParts); var suffix = string.Concat(SuffixDisplayParts); return string.Concat(prefix, display, suffix); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.SignatureHelp { internal class FSharpSignatureHelpParameter { /// <summary> /// The name of this parameter. /// </summary> public string Name { get; } /// <summary> /// Documentation for this parameter. This should normally be presented to the user when /// this parameter is selected. /// </summary> public Func<CancellationToken, IEnumerable<TaggedText>> DocumentationFactory { get; } /// <summary> /// Display parts to show before the normal display parts for the parameter. /// </summary> public IList<TaggedText> PrefixDisplayParts { get; } /// <summary> /// Display parts to show after the normal display parts for the parameter. /// </summary> public IList<TaggedText> SuffixDisplayParts { get; } /// <summary> /// Display parts for this parameter. This should normally be presented to the user as part /// of the entire signature display. /// </summary> public IList<TaggedText> DisplayParts { get; } /// <summary> /// True if this parameter is optional or not. Optional parameters may be presented in a /// different manner to users. /// </summary> public bool IsOptional { get; } /// <summary> /// Display parts for this parameter that should be presented to the user when this /// parameter is selected. /// </summary> public IList<TaggedText> SelectedDisplayParts { get; } private static readonly Func<CancellationToken, IEnumerable<TaggedText>> s_emptyDocumentationFactory = _ => SpecializedCollections.EmptyEnumerable<TaggedText>(); public FSharpSignatureHelpParameter( string name, bool isOptional, Func<CancellationToken, IEnumerable<TaggedText>> documentationFactory, IEnumerable<TaggedText> displayParts, IEnumerable<TaggedText> prefixDisplayParts = null, IEnumerable<TaggedText> suffixDisplayParts = null, IEnumerable<TaggedText> selectedDisplayParts = null) { this.Name = name ?? string.Empty; this.IsOptional = isOptional; this.DocumentationFactory = documentationFactory ?? s_emptyDocumentationFactory; this.DisplayParts = displayParts.ToImmutableArrayOrEmpty(); this.PrefixDisplayParts = prefixDisplayParts.ToImmutableArrayOrEmpty(); this.SuffixDisplayParts = suffixDisplayParts.ToImmutableArrayOrEmpty(); this.SelectedDisplayParts = selectedDisplayParts.ToImmutableArrayOrEmpty(); } internal IEnumerable<TaggedText> GetAllParts() { return this.PrefixDisplayParts.Concat(this.DisplayParts) .Concat(this.SuffixDisplayParts) .Concat(this.SelectedDisplayParts); } public override string ToString() { var prefix = string.Concat(PrefixDisplayParts); var display = string.Concat(DisplayParts); var suffix = string.Concat(SuffixDisplayParts); return string.Concat(prefix, display, suffix); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Tools/ExternalAccess/Razor/IRazorDocumentPropertiesService.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 enable annotations namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal interface IRazorDocumentPropertiesService { /// <summary> /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built. /// </summary> public bool DesignTimeOnly { get; } /// <summary> /// The LSP client name that should get the diagnostics produced by this document; any other source /// will not show these diagnostics. For example, razor uses this to exclude diagnostics from the error list /// so that they can handle the final display. /// If null, the diagnostics do not have this special handling. /// </summary> public string? DiagnosticsLspClientName { 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 enable annotations namespace Microsoft.CodeAnalysis.ExternalAccess.Razor { internal interface IRazorDocumentPropertiesService { /// <summary> /// True if the source code contained in the document is only used in design-time (e.g. for completion), /// but is not passed to the compiler when the containing project is built. /// </summary> public bool DesignTimeOnly { get; } /// <summary> /// The LSP client name that should get the diagnostics produced by this document; any other source /// will not show these diagnostics. For example, razor uses this to exclude diagnostics from the error list /// so that they can handle the final display. /// If null, the diagnostics do not have this special handling. /// </summary> public string? DiagnosticsLspClientName { get; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Core.Cocoa/NavigationCommandHandlers/FindBaseSymbolsCommandHandler.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.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands.Navigation; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers { [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(FindBaseSymbolsCommandHandler))] internal sealed class FindBaseSymbolsCommandHandler : AbstractNavigationCommandHandler<FindBaseSymbolsCommandArgs> { private readonly IAsynchronousOperationListener _asyncListener; public override string DisplayName => nameof(FindBaseSymbolsCommandHandler); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindBaseSymbolsCommandHandler( [ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters, IAsynchronousOperationListenerProvider listenerProvider) : base(streamingPresenters) { Contract.ThrowIfNull(listenerProvider); _asyncListener = listenerProvider.GetListener(FeatureAttribute.FindReferences); } protected override bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context) { var streamingPresenter = base.GetStreamingPresenter(); if (streamingPresenter != null) { _ = StreamingFindBaseSymbolsAsync(document, caretPosition, streamingPresenter); return true; } return false; } private async Task StreamingFindBaseSymbolsAsync( Document document, int caretPosition, IStreamingFindUsagesPresenter presenter) { try { using var token = _asyncListener.BeginAsyncOperation(nameof(StreamingFindBaseSymbolsAsync)); var (context, cancellationToken) = presenter.StartSearch(EditorFeaturesResources.Navigating, supportsReferences: true); using (Logger.LogBlock( FunctionId.CommandHandler_FindAllReference, KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"), cancellationToken)) { try { var relevantSymbol = await FindUsagesHelpers.GetRelevantSymbolAndProjectAtPositionAsync(document, caretPosition, cancellationToken).ConfigureAwait(false); var overriddenSymbol = relevantSymbol?.symbol.GetOverriddenMember(); while (overriddenSymbol != null) { if (cancellationToken.IsCancellationRequested) { return; } var definitionItem = overriddenSymbol.ToNonClassifiedDefinitionItem(document.Project.Solution, true); await context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false); // try getting the next one overriddenSymbol = overriddenSymbol.GetOverriddenMember(); } } finally { await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } } catch (OperationCanceledException) { } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.FindUsages; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.Commanding; using Microsoft.VisualStudio.Text.Editor.Commanding.Commands.Navigation; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; using VSCommanding = Microsoft.VisualStudio.Commanding; namespace Microsoft.CodeAnalysis.Editor.Implementation.NavigationCommandHandlers { [Export(typeof(VSCommanding.ICommandHandler))] [ContentType(ContentTypeNames.RoslynContentType)] [Name(nameof(FindBaseSymbolsCommandHandler))] internal sealed class FindBaseSymbolsCommandHandler : AbstractNavigationCommandHandler<FindBaseSymbolsCommandArgs> { private readonly IAsynchronousOperationListener _asyncListener; public override string DisplayName => nameof(FindBaseSymbolsCommandHandler); [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FindBaseSymbolsCommandHandler( [ImportMany] IEnumerable<Lazy<IStreamingFindUsagesPresenter>> streamingPresenters, IAsynchronousOperationListenerProvider listenerProvider) : base(streamingPresenters) { Contract.ThrowIfNull(listenerProvider); _asyncListener = listenerProvider.GetListener(FeatureAttribute.FindReferences); } protected override bool TryExecuteCommand(int caretPosition, Document document, CommandExecutionContext context) { var streamingPresenter = base.GetStreamingPresenter(); if (streamingPresenter != null) { _ = StreamingFindBaseSymbolsAsync(document, caretPosition, streamingPresenter); return true; } return false; } private async Task StreamingFindBaseSymbolsAsync( Document document, int caretPosition, IStreamingFindUsagesPresenter presenter) { try { using var token = _asyncListener.BeginAsyncOperation(nameof(StreamingFindBaseSymbolsAsync)); var (context, cancellationToken) = presenter.StartSearch(EditorFeaturesResources.Navigating, supportsReferences: true); using (Logger.LogBlock( FunctionId.CommandHandler_FindAllReference, KeyValueLogMessage.Create(LogType.UserAction, m => m["type"] = "streaming"), cancellationToken)) { try { var relevantSymbol = await FindUsagesHelpers.GetRelevantSymbolAndProjectAtPositionAsync(document, caretPosition, cancellationToken).ConfigureAwait(false); var overriddenSymbol = relevantSymbol?.symbol.GetOverriddenMember(); while (overriddenSymbol != null) { if (cancellationToken.IsCancellationRequested) { return; } var definitionItem = overriddenSymbol.ToNonClassifiedDefinitionItem(document.Project.Solution, true); await context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false); // try getting the next one overriddenSymbol = overriddenSymbol.GetOverriddenMember(); } } finally { await context.OnCompletedAsync(cancellationToken).ConfigureAwait(false); } } } catch (OperationCanceledException) { } catch (Exception e) when (FatalError.ReportAndCatch(e)) { } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/CSharp/Portable/Simplification/Reducers/CSharpMiscellaneousReducer.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpMiscellaneousReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpMiscellaneousReducer() : base(s_pool) { } private static bool CanRemoveTypeFromParameter( ParameterSyntax parameterSyntax, SemanticModel semanticModel, CancellationToken cancellationToken) { // We reduce any the parameters that are contained inside ParameterList if (parameterSyntax.IsParentKind(SyntaxKind.ParameterList) && parameterSyntax.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression)) { if (parameterSyntax.Type != null) { var annotation = new SyntaxAnnotation(); var newParameterSyntax = parameterSyntax.WithType(null).WithAdditionalAnnotations(annotation); var oldLambda = parameterSyntax.FirstAncestorOrSelf<ParenthesizedLambdaExpressionSyntax>(); var newLambda = oldLambda.ReplaceNode(parameterSyntax, newParameterSyntax); var speculationAnalyzer = new SpeculationAnalyzer(oldLambda, newLambda, semanticModel, cancellationToken); newParameterSyntax = (ParameterSyntax)speculationAnalyzer.ReplacedExpression.GetAnnotatedNodesAndTokens(annotation).First(); var oldSymbol = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken); var newSymbol = speculationAnalyzer.SpeculativeSemanticModel.GetDeclaredSymbol(newParameterSyntax, cancellationToken); if (oldSymbol != null && newSymbol != null && Equals(oldSymbol.Type, newSymbol.Type)) { return !speculationAnalyzer.ReplacementChangesSemantics(); } } } return false; } private static readonly Func<ParameterSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParameter = SimplifyParameter; private static SyntaxNode SimplifyParameter( ParameterSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (CanRemoveTypeFromParameter(node, semanticModel, cancellationToken)) { var newParameterSyntax = node.WithType(null); newParameterSyntax = SimplificationHelpers.CopyAnnotations(node, newParameterSyntax).WithoutAnnotations(Simplifier.Annotation); return newParameterSyntax; } return node; } private static readonly Func<ParenthesizedLambdaExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParenthesizedLambdaExpression = SimplifyParenthesizedLambdaExpression; private static SyntaxNode SimplifyParenthesizedLambdaExpression( ParenthesizedLambdaExpressionSyntax parenthesizedLambda, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (parenthesizedLambda.ParameterList != null && parenthesizedLambda.ParameterList.Parameters.Count == 1) { var parameter = parenthesizedLambda.ParameterList.Parameters.First(); if (CanRemoveTypeFromParameter(parameter, semanticModel, cancellationToken)) { var newParameterSyntax = parameter.WithType(null); var newSimpleLambda = SyntaxFactory.SimpleLambdaExpression( parenthesizedLambda.AsyncKeyword, newParameterSyntax.WithTrailingTrivia(parenthesizedLambda.ParameterList.GetTrailingTrivia()), parenthesizedLambda.ArrowToken, parenthesizedLambda.Body); return SimplificationHelpers.CopyAnnotations(parenthesizedLambda, newSimpleLambda).WithoutAnnotations(Simplifier.Annotation); } } return parenthesizedLambda; } private static readonly Func<BlockSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyBlock = SimplifyBlock; private static SyntaxNode SimplifyBlock( BlockSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (node.Statements.Count != 1) { return node; } if (!CanHaveEmbeddedStatement(node.Parent)) { return node; } switch (optionSet.GetOption(CSharpCodeStyleOptions.PreferBraces).Value) { case PreferBracesPreference.Always: default: return node; case PreferBracesPreference.WhenMultiline: // Braces are optional in several scenarios for 'when_multiline', but are only automatically removed // in a subset of cases where all of the following are met: // // 1. This is an 'if' statement // 1. The 'if' statement does not have an 'else' clause and is not part of a larger 'if'/'else if'/'else' sequence // 2. The 'if' statement is not considered multiline if (!node.Parent.IsKind(SyntaxKind.IfStatement)) { // Braces are only removed for 'if' statements return node; } if (node.Parent.IsParentKind(SyntaxKind.IfStatement, SyntaxKind.ElseClause)) { // Braces are not removed from more complicated 'if' sequences return node; } if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Statements[0].GetFirstToken(), node.Statements[0].GetLastToken())) { // Braces are not removed when the embedded statement is multiline return node; } if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Parent.GetFirstToken(), node.GetFirstToken().GetPreviousToken())) { // Braces are not removed when the part of the 'if' statement preceding the embedded statement // is multiline. return node; } break; case PreferBracesPreference.None: break; } return node.Statements[0]; } private static bool CanHaveEmbeddedStatement(SyntaxNode node) { if (node != null) { switch (node.Kind()) { case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.UsingStatement: case SyntaxKind.LockStatement: 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpMiscellaneousReducer : AbstractCSharpReducer { private static readonly ObjectPool<IReductionRewriter> s_pool = new( () => new Rewriter(s_pool)); public CSharpMiscellaneousReducer() : base(s_pool) { } private static bool CanRemoveTypeFromParameter( ParameterSyntax parameterSyntax, SemanticModel semanticModel, CancellationToken cancellationToken) { // We reduce any the parameters that are contained inside ParameterList if (parameterSyntax.IsParentKind(SyntaxKind.ParameterList) && parameterSyntax.Parent.IsParentKind(SyntaxKind.ParenthesizedLambdaExpression)) { if (parameterSyntax.Type != null) { var annotation = new SyntaxAnnotation(); var newParameterSyntax = parameterSyntax.WithType(null).WithAdditionalAnnotations(annotation); var oldLambda = parameterSyntax.FirstAncestorOrSelf<ParenthesizedLambdaExpressionSyntax>(); var newLambda = oldLambda.ReplaceNode(parameterSyntax, newParameterSyntax); var speculationAnalyzer = new SpeculationAnalyzer(oldLambda, newLambda, semanticModel, cancellationToken); newParameterSyntax = (ParameterSyntax)speculationAnalyzer.ReplacedExpression.GetAnnotatedNodesAndTokens(annotation).First(); var oldSymbol = semanticModel.GetDeclaredSymbol(parameterSyntax, cancellationToken); var newSymbol = speculationAnalyzer.SpeculativeSemanticModel.GetDeclaredSymbol(newParameterSyntax, cancellationToken); if (oldSymbol != null && newSymbol != null && Equals(oldSymbol.Type, newSymbol.Type)) { return !speculationAnalyzer.ReplacementChangesSemantics(); } } } return false; } private static readonly Func<ParameterSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParameter = SimplifyParameter; private static SyntaxNode SimplifyParameter( ParameterSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (CanRemoveTypeFromParameter(node, semanticModel, cancellationToken)) { var newParameterSyntax = node.WithType(null); newParameterSyntax = SimplificationHelpers.CopyAnnotations(node, newParameterSyntax).WithoutAnnotations(Simplifier.Annotation); return newParameterSyntax; } return node; } private static readonly Func<ParenthesizedLambdaExpressionSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyParenthesizedLambdaExpression = SimplifyParenthesizedLambdaExpression; private static SyntaxNode SimplifyParenthesizedLambdaExpression( ParenthesizedLambdaExpressionSyntax parenthesizedLambda, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (parenthesizedLambda.ParameterList != null && parenthesizedLambda.ParameterList.Parameters.Count == 1) { var parameter = parenthesizedLambda.ParameterList.Parameters.First(); if (CanRemoveTypeFromParameter(parameter, semanticModel, cancellationToken)) { var newParameterSyntax = parameter.WithType(null); var newSimpleLambda = SyntaxFactory.SimpleLambdaExpression( parenthesizedLambda.AsyncKeyword, newParameterSyntax.WithTrailingTrivia(parenthesizedLambda.ParameterList.GetTrailingTrivia()), parenthesizedLambda.ArrowToken, parenthesizedLambda.Body); return SimplificationHelpers.CopyAnnotations(parenthesizedLambda, newSimpleLambda).WithoutAnnotations(Simplifier.Annotation); } } return parenthesizedLambda; } private static readonly Func<BlockSyntax, SemanticModel, OptionSet, CancellationToken, SyntaxNode> s_simplifyBlock = SimplifyBlock; private static SyntaxNode SimplifyBlock( BlockSyntax node, SemanticModel semanticModel, OptionSet optionSet, CancellationToken cancellationToken) { if (node.Statements.Count != 1) { return node; } if (!CanHaveEmbeddedStatement(node.Parent)) { return node; } switch (optionSet.GetOption(CSharpCodeStyleOptions.PreferBraces).Value) { case PreferBracesPreference.Always: default: return node; case PreferBracesPreference.WhenMultiline: // Braces are optional in several scenarios for 'when_multiline', but are only automatically removed // in a subset of cases where all of the following are met: // // 1. This is an 'if' statement // 1. The 'if' statement does not have an 'else' clause and is not part of a larger 'if'/'else if'/'else' sequence // 2. The 'if' statement is not considered multiline if (!node.Parent.IsKind(SyntaxKind.IfStatement)) { // Braces are only removed for 'if' statements return node; } if (node.Parent.IsParentKind(SyntaxKind.IfStatement, SyntaxKind.ElseClause)) { // Braces are not removed from more complicated 'if' sequences return node; } if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Statements[0].GetFirstToken(), node.Statements[0].GetLastToken())) { // Braces are not removed when the embedded statement is multiline return node; } if (!FormattingRangeHelper.AreTwoTokensOnSameLine(node.Parent.GetFirstToken(), node.GetFirstToken().GetPreviousToken())) { // Braces are not removed when the part of the 'if' statement preceding the embedded statement // is multiline. return node; } break; case PreferBracesPreference.None: break; } return node.Statements[0]; } private static bool CanHaveEmbeddedStatement(SyntaxNode node) { if (node != null) { switch (node.Kind()) { case SyntaxKind.IfStatement: case SyntaxKind.ElseClause: case SyntaxKind.ForStatement: case SyntaxKind.ForEachStatement: case SyntaxKind.ForEachVariableStatement: case SyntaxKind.WhileStatement: case SyntaxKind.DoStatement: case SyntaxKind.UsingStatement: case SyntaxKind.LockStatement: return true; } } return false; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Utilities/ImportsStatementComparer.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.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities Friend Class ImportsStatementComparer Implements IComparer(Of ImportsStatementSyntax) Public Shared ReadOnly SystemFirstInstance As IComparer(Of ImportsStatementSyntax) = New ImportsStatementComparer(TokenComparer.SystemFirstInstance) Public Shared ReadOnly NormalInstance As IComparer(Of ImportsStatementSyntax) = New ImportsStatementComparer(TokenComparer.NormalInstance) Private ReadOnly _importsClauseComparer As IComparer(Of ImportsClauseSyntax) Public Sub New(tokenComparer As IComparer(Of SyntaxToken)) Debug.Assert(tokenComparer IsNot Nothing) Me._importsClauseComparer = New ImportsClauseComparer(tokenComparer) End Sub Public Function Compare(directive1 As ImportsStatementSyntax, directive2 As ImportsStatementSyntax) As Integer Implements IComparer(Of ImportsStatementSyntax).Compare If directive1 Is directive2 Then Return 0 End If ' the clauses will already be sorted by now. If directive1.ImportsClauses.Count = 0 And directive2.ImportsClauses.Count = 0 Then Return 0 ElseIf directive1.ImportsClauses.Count = 0 Then Return -1 ElseIf directive2.ImportsClauses.Count = 0 Then Return 1 Else Return _importsClauseComparer.Compare(directive1.ImportsClauses(0), directive2.ImportsClauses(0)) End If End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Utilities Friend Class ImportsStatementComparer Implements IComparer(Of ImportsStatementSyntax) Public Shared ReadOnly SystemFirstInstance As IComparer(Of ImportsStatementSyntax) = New ImportsStatementComparer(TokenComparer.SystemFirstInstance) Public Shared ReadOnly NormalInstance As IComparer(Of ImportsStatementSyntax) = New ImportsStatementComparer(TokenComparer.NormalInstance) Private ReadOnly _importsClauseComparer As IComparer(Of ImportsClauseSyntax) Public Sub New(tokenComparer As IComparer(Of SyntaxToken)) Debug.Assert(tokenComparer IsNot Nothing) Me._importsClauseComparer = New ImportsClauseComparer(tokenComparer) End Sub Public Function Compare(directive1 As ImportsStatementSyntax, directive2 As ImportsStatementSyntax) As Integer Implements IComparer(Of ImportsStatementSyntax).Compare If directive1 Is directive2 Then Return 0 End If ' the clauses will already be sorted by now. If directive1.ImportsClauses.Count = 0 And directive2.ImportsClauses.Count = 0 Then Return 0 ElseIf directive1.ImportsClauses.Count = 0 Then Return -1 ElseIf directive2.ImportsClauses.Count = 0 Then Return 1 Else Return _importsClauseComparer.Compare(directive1.ImportsClauses(0), directive2.ImportsClauses(0)) End If End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Test/Symbol/Symbols/ModuleInitializers/IgnoredTests.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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class IgnoredTests : CSharpTestBase { [Fact] public void IgnoredOnReturnValue() { string source = @" using System.Runtime.CompilerServices; class C { [return: ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnMethodParameter() { string source = @" using System.Runtime.CompilerServices; class C { internal static void M([ModuleInitializer] int p) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnGenericParameter() { string source = @" using System.Runtime.CompilerServices; class C { internal static void M<[ModuleInitializer] T>() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnClass() { string source = @" using System.Runtime.CompilerServices; [ModuleInitializer] class C { internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnEvent() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public event System.Action E; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnProperty() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public int P { get; set; } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnIndexer() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public int this[int p] => p; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnField() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public int F; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnModule() { string source = @" using System.Runtime.CompilerServices; [module: ModuleInitializer] namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnAssembly() { string source = @" using System.Runtime.CompilerServices; [assembly: ModuleInitializer] namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredWhenConstructorArgumentIsSpecified() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer(42)] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { public ModuleInitializerAttribute(int p) { } } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols.ModuleInitializers { [CompilerTrait(CompilerFeature.ModuleInitializers)] public sealed class IgnoredTests : CSharpTestBase { [Fact] public void IgnoredOnReturnValue() { string source = @" using System.Runtime.CompilerServices; class C { [return: ModuleInitializer] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnMethodParameter() { string source = @" using System.Runtime.CompilerServices; class C { internal static void M([ModuleInitializer] int p) { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnGenericParameter() { string source = @" using System.Runtime.CompilerServices; class C { internal static void M<[ModuleInitializer] T>() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnClass() { string source = @" using System.Runtime.CompilerServices; [ModuleInitializer] class C { internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnEvent() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public event System.Action E; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnProperty() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public int P { get; set; } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnIndexer() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public int this[int p] => p; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnField() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer] public int F; } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnModule() { string source = @" using System.Runtime.CompilerServices; [module: ModuleInitializer] namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredOnAssembly() { string source = @" using System.Runtime.CompilerServices; [assembly: ModuleInitializer] namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } [Fact] public void IgnoredWhenConstructorArgumentIsSpecified() { string source = @" using System.Runtime.CompilerServices; class C { [ModuleInitializer(42)] internal static void M() { } } namespace System.Runtime.CompilerServices { class ModuleInitializerAttribute : System.Attribute { public ModuleInitializerAttribute(int p) { } } } "; CompileAndVerify( source, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All), symbolValidator: module => { Assert.Equal(MetadataImportOptions.All, ((PEModuleSymbol)module).ImportOptions); var rootModuleType = (TypeSymbol)module.GlobalNamespace.GetMember("<Module>"); Assert.Null(rootModuleType.GetMember(".cctor")); }); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/ExpressionEvaluator/VisualBasic/Source/ExpressionCompiler/Rewriters/CapturedVariableRewriter.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class CapturedVariableRewriter Inherits BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator Friend Shared Function Rewrite( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), node As BoundNode, diagnostics As DiagnosticBag) As BoundNode Dim rewriter = New CapturedVariableRewriter(targetMethodMeParameter, displayClassVariables, diagnostics) Return rewriter.Visit(node) End Function Private ReadOnly _targetMethodMeParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _diagnostics As DiagnosticBag Private Sub New( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), diagnostics As DiagnosticBag) _targetMethodMeParameter = targetMethodMeParameter _displayClassVariables = displayClassVariables _diagnostics = diagnostics End Sub Public Overrides Function Visit(node As BoundNode) As BoundNode ' Ignore nodes that will be rewritten to literals in the LocalRewriter. If TryCast(node, BoundExpression)?.ConstantValueOpt IsNot Nothing Then Return node End If Return MyBase.Visit(node) End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Dim rewrittenLocals = node.Locals.WhereAsArray(AddressOf IncludeLocal) Dim rewrittenStatements = VisitList(node.Statements) Return node.Update(node.StatementListSyntax, rewrittenLocals, rewrittenStatements) End Function Private Function IncludeLocal(local As LocalSymbol) As Boolean Return Not local.IsStatic AndAlso (local.IsCompilerGenerated OrElse local.Name Is Nothing OrElse GetVariable(local.Name) Is Nothing) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local = node.LocalSymbol If Not local.IsCompilerGenerated Then Dim syntax = node.Syntax Dim staticLocal = TryCast(local, EEStaticLocalSymbol) If staticLocal IsNot Nothing Then Dim receiver = If(_targetMethodMeParameter Is Nothing, Nothing, GetRewrittenMeParameter(syntax, New BoundMeReference(syntax, _targetMethodMeParameter.Type))) Dim result = staticLocal.ToBoundExpression(receiver, syntax, node.IsLValue) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If Dim variable = GetVariable(local.Name) If variable IsNot Nothing Then Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If End If Return node End Function Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode Return RewriteParameter(node.Syntax, node.ParameterSymbol, node) End Function Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode ' Rewrite as a "Me" reference with a conversion ' to the base type and with no virtual calls. Debug.Assert(node.SuppressVirtualCalls) Dim syntax = node.Syntax Dim meParameter = Me.GetRewrittenMeParameter(syntax, node) Debug.Assert(meParameter.Type.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim baseType = node.Type Debug.Assert(baseType.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim result = New BoundDirectCast( syntax:=syntax, operand:=meParameter, conversionKind:=ConversionKind.WideningReference, ' From a class to its base class. suppressVirtualCalls:=node.SuppressVirtualCalls, constantValueOpt:=Nothing, relaxationLambdaOpt:=Nothing, type:=baseType) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode ' MyClass is just Me with virtual calls suppressed. Debug.Assert(node.SuppressVirtualCalls) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode ' ValueTypeMe is just Me with IsLValue true. Debug.Assert(node.IsLValue) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Private Function GetRewrittenMeParameter(syntax As SyntaxNode, node As BoundExpression) As BoundExpression If _targetMethodMeParameter Is Nothing Then ReportMissingMe(node.Syntax) Return node End If Dim result = RewriteParameter(syntax, _targetMethodMeParameter, node) Debug.Assert(result IsNot Nothing) Return result End Function Private Function RewriteParameter(syntax As SyntaxNode, symbol As ParameterSymbol, node As BoundExpression) As BoundExpression Dim name As String = symbol.Name Dim variable = Me.GetVariable(name) If variable Is Nothing Then ' The state machine case is for async lambdas. The state machine ' will have a hoisted "me" field if it needs access to the containing ' display class, but the display class may not have a "me" field. If symbol.Type.IsClosureOrStateMachineType() AndAlso GeneratedNameParser.GetKind(name) <> GeneratedNameKind.TransparentIdentifier Then ReportMissingMe(syntax) End If Return If(TryCast(node, BoundParameter), New BoundParameter(syntax, symbol, node.IsLValue, node.SuppressVirtualCalls, symbol.Type)) End If Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(result.Type.BaseTypeNoUseSiteDiagnostics, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Private Sub ReportMissingMe(syntax As SyntaxNode) _diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, syntax.ToString()), syntax.GetLocation())) End Sub Private Function GetVariable(name As String) As DisplayClassVariable Dim variable As DisplayClassVariable = Nothing _displayClassVariables.TryGetValue(name, variable) Return variable End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator Friend NotInheritable Class CapturedVariableRewriter Inherits BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator Friend Shared Function Rewrite( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), node As BoundNode, diagnostics As DiagnosticBag) As BoundNode Dim rewriter = New CapturedVariableRewriter(targetMethodMeParameter, displayClassVariables, diagnostics) Return rewriter.Visit(node) End Function Private ReadOnly _targetMethodMeParameter As ParameterSymbol Private ReadOnly _displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable) Private ReadOnly _diagnostics As DiagnosticBag Private Sub New( targetMethodMeParameter As ParameterSymbol, displayClassVariables As ImmutableDictionary(Of String, DisplayClassVariable), diagnostics As DiagnosticBag) _targetMethodMeParameter = targetMethodMeParameter _displayClassVariables = displayClassVariables _diagnostics = diagnostics End Sub Public Overrides Function Visit(node As BoundNode) As BoundNode ' Ignore nodes that will be rewritten to literals in the LocalRewriter. If TryCast(node, BoundExpression)?.ConstantValueOpt IsNot Nothing Then Return node End If Return MyBase.Visit(node) End Function Public Overrides Function VisitBlock(node As BoundBlock) As BoundNode Dim rewrittenLocals = node.Locals.WhereAsArray(AddressOf IncludeLocal) Dim rewrittenStatements = VisitList(node.Statements) Return node.Update(node.StatementListSyntax, rewrittenLocals, rewrittenStatements) End Function Private Function IncludeLocal(local As LocalSymbol) As Boolean Return Not local.IsStatic AndAlso (local.IsCompilerGenerated OrElse local.Name Is Nothing OrElse GetVariable(local.Name) Is Nothing) End Function Public Overrides Function VisitLocal(node As BoundLocal) As BoundNode Dim local = node.LocalSymbol If Not local.IsCompilerGenerated Then Dim syntax = node.Syntax Dim staticLocal = TryCast(local, EEStaticLocalSymbol) If staticLocal IsNot Nothing Then Dim receiver = If(_targetMethodMeParameter Is Nothing, Nothing, GetRewrittenMeParameter(syntax, New BoundMeReference(syntax, _targetMethodMeParameter.Type))) Dim result = staticLocal.ToBoundExpression(receiver, syntax, node.IsLValue) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If Dim variable = GetVariable(local.Name) If variable IsNot Nothing Then Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(node.Type, result.Type, TypeCompareKind.ConsiderEverything)) Return result End If End If Return node End Function Public Overrides Function VisitParameter(node As BoundParameter) As BoundNode Return RewriteParameter(node.Syntax, node.ParameterSymbol, node) End Function Public Overrides Function VisitMeReference(node As BoundMeReference) As BoundNode Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitMyBaseReference(node As BoundMyBaseReference) As BoundNode ' Rewrite as a "Me" reference with a conversion ' to the base type and with no virtual calls. Debug.Assert(node.SuppressVirtualCalls) Dim syntax = node.Syntax Dim meParameter = Me.GetRewrittenMeParameter(syntax, node) Debug.Assert(meParameter.Type.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim baseType = node.Type Debug.Assert(baseType.TypeKind = TypeKind.Class) ' Illegal in structures and modules. Dim result = New BoundDirectCast( syntax:=syntax, operand:=meParameter, conversionKind:=ConversionKind.WideningReference, ' From a class to its base class. suppressVirtualCalls:=node.SuppressVirtualCalls, constantValueOpt:=Nothing, relaxationLambdaOpt:=Nothing, type:=baseType) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Public Overrides Function VisitMyClassReference(node As BoundMyClassReference) As BoundNode ' MyClass is just Me with virtual calls suppressed. Debug.Assert(node.SuppressVirtualCalls) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Public Overrides Function VisitValueTypeMeReference(node As BoundValueTypeMeReference) As BoundNode ' ValueTypeMe is just Me with IsLValue true. Debug.Assert(node.IsLValue) Return Me.GetRewrittenMeParameter(node.Syntax, node) End Function Private Function GetRewrittenMeParameter(syntax As SyntaxNode, node As BoundExpression) As BoundExpression If _targetMethodMeParameter Is Nothing Then ReportMissingMe(node.Syntax) Return node End If Dim result = RewriteParameter(syntax, _targetMethodMeParameter, node) Debug.Assert(result IsNot Nothing) Return result End Function Private Function RewriteParameter(syntax As SyntaxNode, symbol As ParameterSymbol, node As BoundExpression) As BoundExpression Dim name As String = symbol.Name Dim variable = Me.GetVariable(name) If variable Is Nothing Then ' The state machine case is for async lambdas. The state machine ' will have a hoisted "me" field if it needs access to the containing ' display class, but the display class may not have a "me" field. If symbol.Type.IsClosureOrStateMachineType() AndAlso GeneratedNameParser.GetKind(name) <> GeneratedNameKind.TransparentIdentifier Then ReportMissingMe(syntax) End If Return If(TryCast(node, BoundParameter), New BoundParameter(syntax, symbol, node.IsLValue, node.SuppressVirtualCalls, symbol.Type)) End If Dim result = variable.ToBoundExpression(syntax, node.IsLValue, node.SuppressVirtualCalls) Debug.Assert(TypeSymbol.Equals(result.Type, node.Type, TypeCompareKind.ConsiderEverything) OrElse TypeSymbol.Equals(result.Type.BaseTypeNoUseSiteDiagnostics, node.Type, TypeCompareKind.ConsiderEverything)) Return result End Function Private Sub ReportMissingMe(syntax As SyntaxNode) _diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_UseOfKeywordNotInInstanceMethod1, syntax.ToString()), syntax.GetLocation())) End Sub Private Function GetVariable(name As String) As DisplayClassVariable Dim variable As DisplayClassVariable = Nothing _displayClassVariables.TryGetValue(name, variable) Return variable End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Portable/Scanner/Scanner.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax ''' <summary> ''' Creates red tokens for a stream of text ''' </summary> Friend Class Scanner Implements IDisposable Private Delegate Function ScanTriviaFunc() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Private Shared ReadOnly s_scanNoTriviaFunc As ScanTriviaFunc = Function() Nothing Private ReadOnly _scanSingleLineTriviaFunc As ScanTriviaFunc = AddressOf ScanSingleLineTrivia Protected _lineBufferOffset As Integer ' marks the next character to read from _buffer Private _endOfTerminatorTrivia As Integer ' marks how far scanner may have scanned ahead for terminator trivia. This may be greater than _lineBufferOffset Friend Const BadTokenCountLimit As Integer = 200 Private _badTokenCount As Integer ' cumulative count of bad tokens produced Private ReadOnly _sbPooled As PooledStringBuilder = PooledStringBuilder.GetInstance ''' <summary> ''' DO NOT USE DIRECTLY. ''' USE GetScratch() ''' </summary> Private ReadOnly _sb As StringBuilder = _sbPooled.Builder Private ReadOnly _triviaListPool As New SyntaxListPool Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _stringTable As StringTable = StringTable.GetInstance() Private ReadOnly _quickTokenTable As TextKeyedCache(Of SyntaxToken) = TextKeyedCache(Of SyntaxToken).GetInstance Public Const TABLE_LIMIT = 512 Private Shared ReadOnly s_keywordKindFactory As Func(Of String, SyntaxKind) = Function(spelling) KeywordTable.TokenOfString(spelling) Private Shared ReadOnly s_keywordsObjsPool As ObjectPool(Of CachingIdentityFactory(Of String, SyntaxKind)) = CachingIdentityFactory(Of String, SyntaxKind).CreatePool(TABLE_LIMIT, s_keywordKindFactory) Private ReadOnly _KeywordsObjs As CachingIdentityFactory(Of String, SyntaxKind) = s_keywordsObjsPool.Allocate() Private Shared ReadOnly s_idTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, IdentifierTokenSyntax))( Function() New CachingFactory(Of TokenParts, IdentifierTokenSyntax)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _idTable As CachingFactory(Of TokenParts, IdentifierTokenSyntax) = s_idTablePool.Allocate() Private Shared ReadOnly s_kwTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, KeywordSyntax))( Function() New CachingFactory(Of TokenParts, KeywordSyntax)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _kwTable As CachingFactory(Of TokenParts, KeywordSyntax) = s_kwTablePool.Allocate Private Shared ReadOnly s_punctTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, PunctuationSyntax))( Function() New CachingFactory(Of TokenParts, PunctuationSyntax)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _punctTable As CachingFactory(Of TokenParts, PunctuationSyntax) = s_punctTablePool.Allocate() Private Shared ReadOnly s_literalTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, SyntaxToken))( Function() New CachingFactory(Of TokenParts, SyntaxToken)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _literalTable As CachingFactory(Of TokenParts, SyntaxToken) = s_literalTablePool.Allocate Private Shared ReadOnly s_wslTablePool As New ObjectPool(Of CachingFactory(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)))( Function() New CachingFactory(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode))(TABLE_LIMIT, s_wsListFactory, s_wsListKeyHasher, s_wsListKeyEquality)) Private ReadOnly _wslTable As CachingFactory(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) = s_wslTablePool.Allocate Private Shared ReadOnly s_wsTablePool As New ObjectPool(Of CachingFactory(Of TriviaKey, SyntaxTrivia))( Function() CreateWsTable()) Private ReadOnly _wsTable As CachingFactory(Of TriviaKey, SyntaxTrivia) = s_wsTablePool.Allocate Private ReadOnly _isScanningForExpressionCompiler As Boolean Private _isDisposed As Boolean Private Function GetScratch() As StringBuilder ' the normal pattern is that we clean scratch after use. ' hitting this assert very likely indicates that you ' did not release scratch content or worse trying to use ' scratch in two places at a time. Debug.Assert(_sb.Length = 0, "trying to use dirty buffer?") Return _sb End Function #Region "Public interface" Friend Sub New(textToScan As SourceText, options As VisualBasicParseOptions, Optional isScanningForExpressionCompiler As Boolean = False) Debug.Assert(textToScan IsNot Nothing) _lineBufferOffset = 0 _buffer = textToScan _bufferLen = textToScan.Length _curPage = GetPage(0) _options = options _scannerPreprocessorState = New PreprocessorState(GetPreprocessorConstants(options)) _isScanningForExpressionCompiler = isScanningForExpressionCompiler End Sub Friend Sub Dispose() Implements IDisposable.Dispose If Not _isDisposed Then _isDisposed = True _KeywordsObjs.Free() _quickTokenTable.Free() _stringTable.Free() _sbPooled.Free() s_idTablePool.Free(_idTable) s_kwTablePool.Free(_kwTable) s_punctTablePool.Free(_punctTable) s_literalTablePool.Free(_literalTable) s_wslTablePool.Free(_wslTable) s_wsTablePool.Free(_wsTable) For Each p As Page In _pages If p IsNot Nothing Then p.Free() End If Next Array.Clear(_pages, 0, _pages.Length) End If End Sub Friend ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Friend Shared Function GetPreprocessorConstants(options As VisualBasicParseOptions) As ImmutableDictionary(Of String, CConst) If options.PreprocessorSymbols.IsDefaultOrEmpty Then Return ImmutableDictionary(Of String, CConst).Empty End If Dim result = ImmutableDictionary.CreateBuilder(Of String, CConst)(IdentifierComparison.Comparer) For Each symbol In options.PreprocessorSymbols ' The values in options have already been verified result(symbol.Key) = CConst.CreateChecked(symbol.Value) Next Return result.ToImmutable() End Function Private Function GetNextToken(Optional allowLeadingMultilineTrivia As Boolean = False) As SyntaxToken ' Use quick token scanning to see if we can scan a token quickly. Dim quickToken = QuickScanToken(allowLeadingMultilineTrivia) If quickToken.Succeeded Then Dim token = _quickTokenTable.FindItem(quickToken.Chars, quickToken.Start, quickToken.Length, quickToken.HashCode) If token IsNot Nothing Then AdvanceChar(quickToken.Length) If quickToken.TerminatorLength <> 0 Then _endOfTerminatorTrivia = _lineBufferOffset _lineBufferOffset -= quickToken.TerminatorLength End If Return token End If End If Dim scannedToken = ScanNextToken(allowLeadingMultilineTrivia) ' If we quick-scanned a token, but didn't have a actual token cached for it, cache the token we created ' from the regular scanner. If quickToken.Succeeded Then Debug.Assert(quickToken.Length = scannedToken.FullWidth) _quickTokenTable.AddItem(quickToken.Chars, quickToken.Start, quickToken.Length, quickToken.HashCode, scannedToken) End If Return scannedToken End Function Private Function ScanNextToken(allowLeadingMultilineTrivia As Boolean) As SyntaxToken #If DEBUG Then Dim oldOffset = _lineBufferOffset #End If Dim leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) If allowLeadingMultilineTrivia Then leadingTrivia = ScanMultilineTrivia() Else leadingTrivia = ScanLeadingTrivia() ' Special case where the remainder of the line is a comment. Dim length = PeekStartComment(0) If length > 0 Then Return MakeEmptyToken(leadingTrivia) End If End If Dim token = TryScanToken(leadingTrivia) If token Is Nothing Then token = ScanNextCharAsToken(leadingTrivia) End If If _lineBufferOffset > _endOfTerminatorTrivia Then _endOfTerminatorTrivia = _lineBufferOffset End If #If DEBUG Then ' we must always consume as much as returned token's full length or things will go very bad Debug.Assert(oldOffset + token.FullWidth = _lineBufferOffset OrElse oldOffset + token.FullWidth = _endOfTerminatorTrivia OrElse token.FullWidth = 0) #End If Return token End Function Private Function ScanNextCharAsToken(leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Dim token As SyntaxToken If Not CanGet() Then token = MakeEofToken(leadingTrivia) Else _badTokenCount += 1 If _badTokenCount < BadTokenCountLimit Then ' // Don't break up surrogate pairs Dim c = Peek() Dim length = If(IsHighSurrogate(c) AndAlso CanGet(1) AndAlso IsLowSurrogate(Peek(1)), 2, 1) token = MakeBadToken(leadingTrivia, length, ERRID.ERR_IllegalChar) Else ' If we get too many characters that we cannot make sense of, absorb the rest of the input. token = MakeBadToken(leadingTrivia, RemainingLength(), ERRID.ERR_IllegalChar) End If End If Return token End Function ' // SkipToNextConditionalLine advances through the input stream until it finds a (logical) ' // line that has a '#' character as its first non-whitespace, non-continuation character. ' // SkipToNextConditionalLine ignores explicit line continuation. ' TODO: this could be vastly simplified if we could ignore line continuations. Public Function SkipToNextConditionalLine() As TextSpan ' start at current token ResetLineBufferOffset() Dim start = _lineBufferOffset ' if starting not from line start, skip to the next one. Dim prev = PrevToken If Not IsAtNewLine() OrElse (PrevToken IsNot Nothing AndAlso PrevToken.EndsWithEndOfLineOrColonTrivia) Then EatThroughLine() End If Dim condLineStart = _lineBufferOffset While (CanGet()) Dim c As Char = Peek() Select Case (c) Case CARRIAGE_RETURN, LINE_FEED EatThroughLineBreak(c) condLineStart = _lineBufferOffset Continue While Case SPACE, CHARACTER_TABULATION Debug.Assert(IsWhitespace(Peek())) EatWhitespace() Continue While Case _ "a"c, "b"c, "c"c, "d"c, "e"c, "f"c, "g"c, "h"c, "i"c, "j"c, "k"c, "l"c, "m"c, "n"c, "o"c, "p"c, "q"c, "r"c, "s"c, "t"c, "u"c, "v"c, "w"c, "x"c, "y"c, "z"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c, "H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c, "'"c, "_"c EatThroughLine() condLineStart = _lineBufferOffset Continue While Case "#"c, FULLWIDTH_NUMBER_SIGN Exit While Case Else If IsWhitespace(c) Then EatWhitespace() Continue While ElseIf IsNewLine(c) Then EatThroughLineBreak(c) condLineStart = _lineBufferOffset Continue While End If EatThroughLine() condLineStart = _lineBufferOffset Continue While End Select End While ' we did not find # or we have hit EoF. _lineBufferOffset = condLineStart Debug.Assert(_lineBufferOffset >= start AndAlso _lineBufferOffset >= 0) ResetTokens() Return TextSpan.FromBounds(start, condLineStart) End Function Private Sub EatThroughLine() While CanGet() Dim c As Char = Peek() If IsNewLine(c) Then EatThroughLineBreak(c) Return Else AdvanceChar() End If End While End Sub ''' <summary> ''' Gets a chunk of text as a DisabledCode node. ''' </summary> ''' <param name="span">The range of text.</param> ''' <returns>The DisabledCode node.</returns> Friend Function GetDisabledTextAt(span As TextSpan) As SyntaxTrivia If span.Start >= 0 AndAlso span.End <= _bufferLen Then Return SyntaxFactory.DisabledTextTrivia(GetTextNotInterned(span.Start, span.Length)) End If ' TODO: should this be a Require? Throw New ArgumentOutOfRangeException(NameOf(span)) End Function #End Region #Region "Interning" Friend Function GetScratchTextInterned(sb As StringBuilder) As String Dim str = _stringTable.Add(sb) sb.Clear() Return str End Function Friend Shared Function GetScratchText(sb As StringBuilder) As String ' PERF: Special case for the very common case of a string containing a single space Dim str As String If sb.Length = 1 AndAlso sb(0) = " "c Then str = " " Else str = sb.ToString End If sb.Clear() Return str End Function ' This overload of GetScratchText first examines the contents of the StringBuilder to ' see if it matches the given string. If so, then the given string is returned, saving ' the allocation. Private Shared Function GetScratchText(sb As StringBuilder, text As String) As String Dim str As String If StringTable.TextEquals(text, sb) Then str = text Else str = sb.ToString End If sb.Clear() Return str End Function Friend Function Intern(s As String, start As Integer, length As Integer) As String Return _stringTable.Add(s, start, length) End Function Friend Function Intern(s As Char(), start As Integer, length As Integer) As String Return _stringTable.Add(s, start, length) End Function Friend Function Intern(ch As Char) As String Return _stringTable.Add(ch) End Function Friend Function Intern(arr As Char()) As String Return _stringTable.Add(arr) End Function #End Region #Region "Buffer helpers" Private Function NextAre(chars As String) As Boolean Return NextAre(0, chars) End Function Private Function NextAre(offset As Integer, chars As String) As Boolean Debug.Assert(Not String.IsNullOrEmpty(chars)) Dim n = chars.Length If Not CanGet(offset + n - 1) Then Return False For i = 0 To n - 1 If chars(i) <> Peek(offset + i) Then Return False Next Return True End Function Private Function NextIs(offset As Integer, c As Char) As Boolean Return CanGet(offset) AndAlso (Peek(offset) = c) End Function Private Function CanGet() As Boolean Return _lineBufferOffset < _bufferLen End Function Private Function CanGet(num As Integer) As Boolean Debug.Assert(_lineBufferOffset + num >= 0) Debug.Assert(num >= -MaxCharsLookBehind) Return _lineBufferOffset + num < _bufferLen End Function Private Function RemainingLength() As Integer Dim result = _bufferLen - _lineBufferOffset Debug.Assert(CanGet(result - 1)) Return result End Function Private Function GetText(length As Integer) As String Debug.Assert(length > 0) Debug.Assert(CanGet(length - 1)) If length = 1 Then Return GetNextChar() End If Dim str = GetText(_lineBufferOffset, length) AdvanceChar(length) Return str End Function Private Function GetTextNotInterned(length As Integer) As String Debug.Assert(length > 0) Debug.Assert(CanGet(length - 1)) If length = 1 Then ' we will still intern single chars. There could not be too many. Return GetNextChar() End If Dim str = GetTextNotInterned(_lineBufferOffset, length) AdvanceChar(length) Return str End Function Private Sub AdvanceChar(Optional howFar As Integer = 1) Debug.Assert(howFar > 0) Debug.Assert(CanGet(howFar - 1)) _lineBufferOffset += howFar End Sub Private Function GetNextChar() As String Debug.Assert(CanGet) Dim ch = GetChar() _lineBufferOffset += 1 Return ch End Function Private Sub EatThroughLineBreak(StartCharacter As Char) AdvanceChar(LengthOfLineBreak(StartCharacter)) End Sub Private Function SkipLineBreak(StartCharacter As Char, index As Integer) As Integer Return index + LengthOfLineBreak(StartCharacter, index) End Function Private Function LengthOfLineBreak(StartCharacter As Char, Optional here As Integer = 0) As Integer Debug.Assert(CanGet(here)) Debug.Assert(IsNewLine(StartCharacter)) Debug.Assert(StartCharacter = Peek(here)) If StartCharacter = CARRIAGE_RETURN AndAlso NextIs(here + 1, LINE_FEED) Then Return 2 End If Return 1 End Function #End Region #Region "New line and explicit line continuation." ''' <summary> ''' Accept a CR/LF pair or either in isolation as a newline. ''' Make it a statement separator ''' </summary> Private Function ScanNewlineAsStatementTerminator(startCharacter As Char, precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken If _lineBufferOffset < _endOfTerminatorTrivia Then Dim width = LengthOfLineBreak(startCharacter) Return MakeStatementTerminatorToken(precedingTrivia, width) Else Return MakeEmptyToken(precedingTrivia) End If End Function Private Function ScanColonAsStatementTerminator(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As SyntaxToken If _lineBufferOffset < _endOfTerminatorTrivia Then Return MakeColonToken(precedingTrivia, charIsFullWidth) Else Return MakeEmptyToken(precedingTrivia) End If End Function ''' <summary> ''' Accept a CR/LF pair or either in isolation as a newline. ''' Make it a whitespace ''' </summary> Private Function ScanNewlineAsTrivia(StartCharacter As Char) As SyntaxTrivia If LengthOfLineBreak(StartCharacter) = 2 Then Return MakeEndOfLineTriviaCRLF() End If Return MakeEndOfLineTrivia(GetNextChar) End Function Private Function TryGet(num As Integer, ByRef ch As Char) As Boolean If CanGet(num) Then ch = Peek(num) Return True End If Return False End Function Private Function ScanLineContinuation(tList As SyntaxListBuilder) As Boolean Dim ch As Char = ChrW(0) If Not TryGet(0, ch) Then Return False End If If Not IsAfterWhitespace() Then Return False End If If Not IsUnderscore(ch) Then Return False End If Dim here = GetWhitespaceLength(1) TryGet(here, ch) Dim foundComment = IsSingleQuote(ch) Dim atNewLine As Boolean = IsNewLine(ch) If Not foundComment AndAlso Not atNewLine AndAlso CanGet(here) Then Return False End If tList.Add(MakeLineContinuationTrivia(GetText(1))) If here > 1 Then tList.Add(MakeWhiteSpaceTrivia(GetText(here - 1))) End If If foundComment Then Dim comment As SyntaxTrivia = ScanComment() If Not CheckFeatureAvailability(Feature.CommentsAfterLineContinuation) Then comment = comment.WithDiagnostics({ErrorFactory.ErrorInfo(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, New VisualBasicRequiredLanguageVersion(Feature.CommentsAfterLineContinuation.GetLanguageVersion()))}) End If tList.Add(comment) ' Need to call CanGet here to prevent Peek reading past EndOfBuffer. This can happen when file ends with comment but no New Line. If CanGet() Then ch = Peek() atNewLine = IsNewLine(ch) Else Debug.Assert(Not atNewLine) End If End If If atNewLine Then Dim newLine = SkipLineBreak(ch, 0) here = GetWhitespaceLength(newLine) Dim spaces = here - newLine Dim startComment = PeekStartComment(here) ' If the line following the line continuation is blank, or blank with a comment, ' do not include the new line character since that would confuse code handling ' implicit line continuations. (See Scanner::EatLineContinuation.) Otherwise, ' include the new line and any additional spaces as trivia. If startComment = 0 AndAlso CanGet(here) AndAlso Not IsNewLine(Peek(here)) Then tList.Add(MakeEndOfLineTrivia(GetText(newLine))) If spaces > 0 Then tList.Add(MakeWhiteSpaceTrivia(GetText(spaces))) End If End If End If Return True End Function #End Region #Region "Trivia" ''' <summary> ''' Consumes all trivia until a nontrivia char is found ''' </summary> Friend Function ScanMultilineTrivia() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) If Not CanGet() Then Return Nothing End If Dim ch = Peek() ' optimization for a common case ' the ASCII range between ': and ~ , with exception of except "'", "_" and R cannot start trivia If ch > ":"c AndAlso ch <= "~"c AndAlso ch <> "'"c AndAlso ch <> "_"c AndAlso ch <> "R"c AndAlso ch <> "r"c AndAlso ch <> "<"c AndAlso ch <> "="c AndAlso ch <> ">"c Then Return Nothing End If Dim triviaList = _triviaListPool.Allocate() While TryScanSinglePieceOfMultilineTrivia(triviaList) End While Dim result = MakeTriviaArray(triviaList) _triviaListPool.Free(triviaList) Return result End Function ''' <summary> ''' Scans a single piece of trivia ''' </summary> Private Function TryScanSinglePieceOfMultilineTrivia(tList As SyntaxListBuilder) As Boolean If CanGet() Then Dim atNewLine = IsAtNewLine() ' check for XmlDocComment and directives If atNewLine Then If StartsXmlDoc(0) Then Return TryScanXmlDocComment(tList) End If If StartsDirective(0) Then Return TryScanDirective(tList) End If If IsConflictMarkerTrivia() Then ScanConflictMarker(tList) Return True End If End If Dim ch = Peek() If IsWhitespace(ch) Then ' eat until linebreak or non-whitespace Dim wslen = GetWhitespaceLength(1) If atNewLine Then If StartsXmlDoc(wslen) Then Return TryScanXmlDocComment(tList) End If If StartsDirective(wslen) Then Return TryScanDirective(tList) End If End If tList.Add(MakeWhiteSpaceTrivia(GetText(wslen))) Return True ElseIf IsNewLine(ch) Then tList.Add(ScanNewlineAsTrivia(ch)) Return True ElseIf IsUnderscore(ch) Then Return ScanLineContinuation(tList) ElseIf IsColonAndNotColonEquals(ch, offset:=0) Then tList.Add(ScanColonAsTrivia()) Return True End If ' try get a comment Return ScanCommentIfAny(tList) End If Return False End Function ' All conflict markers consist of the same character repeated seven times. If it Is ' a <<<<<<< Or >>>>>>> marker then it Is also followed by a space. Private Shared ReadOnly s_conflictMarkerLength As Integer = "<<<<<<<".Length Private Function IsConflictMarkerTrivia() As Boolean If CanGet() Then Dim ch = Peek() If ch = "<"c OrElse ch = ">"c OrElse ch = "="c Then Dim position = _lineBufferOffset Dim text = _buffer If position = 0 OrElse SyntaxFacts.IsNewLine(text(position - 1)) Then Dim firstCh = _buffer(position) If (position + s_conflictMarkerLength) <= text.Length Then For i = 0 To s_conflictMarkerLength - 1 If text(position + i) <> firstCh Then Return False End If Next If firstCh = "="c Then Return True End If Return (position + s_conflictMarkerLength) < text.Length AndAlso text(position + s_conflictMarkerLength) = " "c End If End If End If End If Return False End Function Private Sub ScanConflictMarker(tList As SyntaxListBuilder) Dim startCh = Peek() ' First create a trivia from the start of this merge conflict marker to the ' end of line/file (whichever comes first). ScanConflictMarkerHeader(tList) ' Now add the newlines as the next trivia. ScanConflictMarkerEndOfLine(tList) If startCh = "="c Then ' Consume everything from the start of the mid-conflict marker to the start of the next ' end-conflict marker. ScanConflictMarkerDisabledText(tList) End If End Sub Private Sub ScanConflictMarkerDisabledText(tList As SyntaxListBuilder) Dim start = _lineBufferOffset While CanGet() Dim ch = Peek() If ch = ">"c AndAlso IsConflictMarkerTrivia() Then Exit While End If AdvanceChar() End While Dim width = _lineBufferOffset - start If width > 0 Then tList.Add(SyntaxFactory.DisabledTextTrivia(GetText(start, width))) End If End Sub Private Sub ScanConflictMarkerEndOfLine(tList As SyntaxListBuilder) Dim start = _lineBufferOffset While CanGet() AndAlso SyntaxFacts.IsNewLine(Peek()) AdvanceChar() End While Dim width = _lineBufferOffset - start If width > 0 Then tList.Add(SyntaxFactory.EndOfLineTrivia(GetText(start, width))) End If End Sub Private Sub ScanConflictMarkerHeader(tList As SyntaxListBuilder) Dim start = _lineBufferOffset While CanGet() Dim ch = Peek() If SyntaxFacts.IsNewLine(ch) Then Exit While End If AdvanceChar() End While Dim trivia = SyntaxFactory.ConflictMarkerTrivia(GetText(start, _lineBufferOffset - start)) trivia = DirectCast(trivia.SetDiagnostics({ErrorFactory.ErrorInfo(ERRID.ERR_Merge_conflict_marker_encountered)}), SyntaxTrivia) tList.Add(trivia) End Sub ' check for '''(~') Private Function StartsXmlDoc(here As Integer) As Boolean Return _options.DocumentationMode >= DocumentationMode.Parse AndAlso CanGet(here + 3) AndAlso IsSingleQuote(Peek(here)) AndAlso IsSingleQuote(Peek(here + 1)) AndAlso IsSingleQuote(Peek(here + 2)) AndAlso Not IsSingleQuote(Peek(here + 3)) End Function ' check for # Private Function StartsDirective(here As Integer) As Boolean If CanGet(here) Then Dim ch = Peek(here) Return IsHash(ch) End If Return False End Function Private Function IsAtNewLine() As Boolean Return _lineBufferOffset = 0 OrElse IsNewLine(Peek(-1)) End Function Private Function IsAfterWhitespace() As Boolean If _lineBufferOffset = 0 Then Return True End If Dim prevChar = Peek(-1) Return IsWhitespace(prevChar) End Function ''' <summary> ''' Scan trivia on one LOGICAL line ''' Will check for whitespace, comment, EoL, implicit line break ''' EoL may be consumed as whitespace only as a part of line continuation ( _ ) ''' </summary> Friend Function ScanSingleLineTrivia() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Dim tList = _triviaListPool.Allocate() ScanSingleLineTrivia(tList) Dim result = MakeTriviaArray(tList) _triviaListPool.Free(tList) Return result End Function Private Sub ScanSingleLineTrivia(tList As SyntaxListBuilder) If IsScanningXmlDoc Then ScanSingleLineTriviaInXmlDoc(tList) Else ScanWhitespaceAndLineContinuations(tList) ScanCommentIfAny(tList) ScanTerminatorTrivia(tList) End If End Sub Private Sub ScanSingleLineTriviaInXmlDoc(tList As SyntaxListBuilder) If CanGet() Then Dim c As Char = Peek() Select Case (c) ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION Dim offsets = CreateOffsetRestorePoint() Dim triviaList = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)() Dim continueLine = ScanXmlTriviaInXmlDoc(c, triviaList) If Not continueLine Then _triviaListPool.Free(triviaList) offsets.Restore() Return End If For i = 0 To triviaList.Count - 1 tList.Add(triviaList(i)) Next _triviaListPool.Free(triviaList) End Select End If End Sub Private Function ScanLeadingTrivia() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Dim tList = _triviaListPool.Allocate() ScanWhitespaceAndLineContinuations(tList) Dim result = MakeTriviaArray(tList) _triviaListPool.Free(tList) Return result End Function Private Sub ScanWhitespaceAndLineContinuations(tList As SyntaxListBuilder) If CanGet() AndAlso IsWhitespace(Peek()) Then tList.Add(ScanWhitespace(1)) ' collect { lineCont, ws } While ScanLineContinuation(tList) End While End If End Sub Private Function ScanSingleLineTrivia(includeFollowingBlankLines As Boolean) As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Dim tList = _triviaListPool.Allocate() ScanSingleLineTrivia(tList) If includeFollowingBlankLines AndAlso IsBlankLine(tList) Then Dim more = _triviaListPool.Allocate() While True Dim offsets = CreateOffsetRestorePoint() _lineBufferOffset = _endOfTerminatorTrivia ScanSingleLineTrivia(more) If Not IsBlankLine(more) Then offsets.Restore() Exit While End If Dim n = more.Count For i = 0 To n - 1 tList.Add(more(i)) Next more.Clear() End While _triviaListPool.Free(more) End If Dim result = tList.ToList() _triviaListPool.Free(tList) Return result End Function ''' <summary> ''' Return True if the builder is a (possibly empty) list of ''' WhitespaceTrivia followed by an EndOfLineTrivia. ''' </summary> Private Shared Function IsBlankLine(tList As SyntaxListBuilder) As Boolean Dim n = tList.Count If n = 0 OrElse tList(n - 1).RawKind <> SyntaxKind.EndOfLineTrivia Then Return False End If For i = 0 To n - 2 If tList(i).RawKind <> SyntaxKind.WhitespaceTrivia Then Return False End If Next Return True End Function Private Sub ScanTerminatorTrivia(tList As SyntaxListBuilder) ' Check for statement terminators ' There are 4 special cases ' 1. [colon ws+]* colon -> colon terminator ' 2. new line -> new line terminator ' 3. colon followed by new line -> colon terminator + new line terminator ' 4. new line followed by new line -> new line terminator + new line terminator ' Case 3 is required to parse single line if's and numeric labels. ' Case 4 is required to limit explicit line continuations to single new line If CanGet() Then Dim ch As Char = Peek() Dim startOfTerminatorTrivia = _lineBufferOffset If IsNewLine(ch) Then tList.Add(ScanNewlineAsTrivia(ch)) ElseIf IsColonAndNotColonEquals(ch, offset:=0) Then tList.Add(ScanColonAsTrivia()) ' collect { ws, colon } Do Dim len = GetWhitespaceLength(0) If Not CanGet(len) Then Exit Do End If ch = Peek(len) If Not IsColonAndNotColonEquals(ch, offset:=len) Then Exit Do End If If len > 0 Then tList.Add(MakeWhiteSpaceTrivia(GetText(len))) End If startOfTerminatorTrivia = _lineBufferOffset tList.Add(ScanColonAsTrivia()) Loop End If _endOfTerminatorTrivia = _lineBufferOffset ' Reset _lineBufferOffset to the start of the terminator trivia. ' When the scanner is asked for the next token, it will return a 0 length terminator or colon token. _lineBufferOffset = startOfTerminatorTrivia End If End Sub Private Function ScanCommentIfAny(tList As SyntaxListBuilder) As Boolean If CanGet() Then ' check for comment Dim comment = ScanComment() If comment IsNot Nothing Then tList.Add(comment) Return True End If End If Return False End Function Private Function GetWhitespaceLength(len As Integer) As Integer ' eat until linebreak or non-whitespace While CanGet(len) AndAlso IsWhitespace(Peek(len)) len += 1 End While Return len End Function Private Function GetXmlWhitespaceLength(len As Integer) As Integer ' eat until linebreak or non-whitespace While CanGet(len) AndAlso IsXmlWhitespace(Peek(len)) len += 1 End While Return len End Function Private Function ScanWhitespace(Optional len As Integer = 0) As VisualBasicSyntaxNode len = GetWhitespaceLength(len) If len > 0 Then Return MakeWhiteSpaceTrivia(GetText(len)) End If Return Nothing End Function Private Function ScanXmlWhitespace(Optional len As Integer = 0) As VisualBasicSyntaxNode len = GetXmlWhitespaceLength(len) If len > 0 Then Return MakeWhiteSpaceTrivia(GetText(len)) End If Return Nothing End Function Private Sub EatWhitespace() Debug.Assert(CanGet) Debug.Assert(IsWhitespace(Peek())) AdvanceChar() ' eat until linebreak or non-whitespace While CanGet() AndAlso IsWhitespace(Peek) AdvanceChar() End While End Sub Private Function PeekStartComment(i As Integer) As Integer If CanGet(i) Then Dim ch = Peek(i) If IsSingleQuote(ch) Then Return 1 ElseIf MatchOneOrAnotherOrFullwidth(ch, "R"c, "r"c) AndAlso CanGet(i + 2) AndAlso MatchOneOrAnotherOrFullwidth(Peek(i + 1), "E"c, "e"c) AndAlso MatchOneOrAnotherOrFullwidth(Peek(i + 2), "M"c, "m"c) Then If Not CanGet(i + 3) OrElse IsNewLine(Peek(i + 3)) Then ' have only 'REM' Return 3 ElseIf Not IsIdentifierPartCharacter(Peek(i + 3)) Then ' have 'REM ' Return 4 End If End If End If Return 0 End Function Private Function ScanComment() As SyntaxTrivia Debug.Assert(CanGet()) Dim length = PeekStartComment(0) If length > 0 Then Dim looksLikeDocComment As Boolean = StartsXmlDoc(0) ' eat all chars until EoL While CanGet(length) AndAlso Not IsNewLine(Peek(length)) length += 1 End While Dim commentTrivia As SyntaxTrivia = MakeCommentTrivia(GetTextNotInterned(length)) If looksLikeDocComment AndAlso _options.DocumentationMode >= DocumentationMode.Diagnose Then commentTrivia = commentTrivia.WithDiagnostics(ErrorFactory.ErrorInfo(ERRID.WRN_XMLDocNotFirstOnLine)) End If Return commentTrivia End If Return Nothing End Function ''' <summary> ''' Return True if the character is a colon, and not part of ":=". ''' </summary> Private Function IsColonAndNotColonEquals(ch As Char, offset As Integer) As Boolean Return IsColon(ch) AndAlso Not TrySkipFollowingEquals(offset + 1) End Function Private Function ScanColonAsTrivia() As SyntaxTrivia Debug.Assert(CanGet()) Debug.Assert(IsColonAndNotColonEquals(Peek(), offset:=0)) Return MakeColonTrivia(GetText(1)) End Function #End Region Private Function ScanTokenCommon(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), ch As Char, fullWidth As Boolean) As SyntaxToken Dim lengthWithMaybeEquals As Integer = 1 Select Case ch Case CARRIAGE_RETURN, LINE_FEED Return ScanNewlineAsStatementTerminator(ch, precedingTrivia) Case NEXT_LINE, LINE_SEPARATOR, PARAGRAPH_SEPARATOR If Not fullWidth Then Return ScanNewlineAsStatementTerminator(ch, precedingTrivia) End If Case " "c, CHARACTER_TABULATION, "'"c Debug.Assert(False, $"Unexpected char: &H{AscW(ch):x}") Return Nothing ' trivia cannot start a token Case "@"c Return MakeAtToken(precedingTrivia, fullWidth) Case "("c Return MakeOpenParenToken(precedingTrivia, fullWidth) Case ")"c Return MakeCloseParenToken(precedingTrivia, fullWidth) Case "{"c Return MakeOpenBraceToken(precedingTrivia, fullWidth) Case "}"c Return MakeCloseBraceToken(precedingTrivia, fullWidth) Case ","c Return MakeCommaToken(precedingTrivia, fullWidth) Case "#"c Dim dl = ScanDateLiteral(precedingTrivia) Return If(dl, MakeHashToken(precedingTrivia, fullWidth)) Case "&"c If CanGet(1) AndAlso BeginsBaseLiteral(Peek(1)) Then Return ScanNumericLiteral(precedingTrivia) End If If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeAmpersandEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeAmpersandToken(precedingTrivia, fullWidth) End If Case "="c Return MakeEqualsToken(precedingTrivia, fullWidth) Case "<"c Return ScanLeftAngleBracket(precedingTrivia, fullWidth, _scanSingleLineTriviaFunc) Case ">"c Return ScanRightAngleBracket(precedingTrivia, fullWidth) Case ":"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeColonEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return ScanColonAsStatementTerminator(precedingTrivia, fullWidth) End If Case "+"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakePlusEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakePlusToken(precedingTrivia, fullWidth) End If Case "-"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeMinusEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeMinusToken(precedingTrivia, fullWidth) End If Case "*"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeAsteriskEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeAsteriskToken(precedingTrivia, fullWidth) End If Case "/"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeSlashEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeSlashToken(precedingTrivia, fullWidth) End If Case "\"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeBackSlashEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeBackslashToken(precedingTrivia, fullWidth) End If Case "^"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeCaretEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeCaretToken(precedingTrivia, fullWidth) End If Case "!"c Return MakeExclamationToken(precedingTrivia, fullWidth) Case "."c If CanGet(1) AndAlso IsDecimalDigit(Peek(1)) Then Return ScanNumericLiteral(precedingTrivia) Else Return MakeDotToken(precedingTrivia, fullWidth) End If Case "0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c Return ScanNumericLiteral(precedingTrivia) Case """"c Return ScanStringLiteral(precedingTrivia) Case "A"c If NextAre(1, "s ") Then ' TODO: do we allow widechars in keywords? AdvanceChar(2) Return MakeKeyword(SyntaxKind.AsKeyword, "As", precedingTrivia) Else Return ScanIdentifierOrKeyword(precedingTrivia) End If Case "E"c If NextAre(1, "nd ") Then ' TODO: do we allow widechars in keywords? AdvanceChar(3) Return MakeKeyword(SyntaxKind.EndKeyword, "End", precedingTrivia) Else Return ScanIdentifierOrKeyword(precedingTrivia) End If Case "I"c If NextAre(1, "f ") Then ' TODO: do we allow widechars in keywords? AdvanceChar(2) Return MakeKeyword(SyntaxKind.IfKeyword, "If", precedingTrivia) Else Return ScanIdentifierOrKeyword(precedingTrivia) End If Case "a"c, "b"c, "c"c, "d"c, "e"c, "f"c, "g"c, "h"c, "i"c, "j"c, "k"c, "l"c, "m"c, "n"c, "o"c, "p"c, "q"c, "r"c, "s"c, "t"c, "u"c, "v"c, "w"c, "x"c, "y"c, "z"c Return ScanIdentifierOrKeyword(precedingTrivia) Case "B"c, "C"c, "D"c, "F"c, "G"c, "H"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c Return ScanIdentifierOrKeyword(precedingTrivia) Case "_"c If CanGet(1) AndAlso IsIdentifierPartCharacter(Peek(1)) Then Return ScanIdentifierOrKeyword(precedingTrivia) End If Dim err As ERRID = ERRID.ERR_ExpectedIdentifier Dim len = GetWhitespaceLength(1) If Not CanGet(len) OrElse IsNewLine(Peek(len)) OrElse PeekStartComment(len) > 0 Then err = ERRID.ERR_LineContWithCommentOrNoPrecSpace End If ' not a line continuation and cannot start identifier. Return MakeBadToken(precedingTrivia, 1, err) Case "["c Return ScanBracketedIdentifier(precedingTrivia) Case "?"c Return MakeQuestionToken(precedingTrivia, fullWidth) Case "%"c If NextIs(1, ">"c) Then Return XmlMakeEndEmbeddedToken(precedingTrivia, _scanSingleLineTriviaFunc) End If Case "$"c, FULLWIDTH_DOLLAR_SIGN If Not fullWidth AndAlso CanGet(1) AndAlso IsDoubleQuote(Peek(1)) Then Return MakePunctuationToken(precedingTrivia, 2, SyntaxKind.DollarSignDoubleQuoteToken) End If End Select If IsIdentifierStartCharacter(ch) Then Return ScanIdentifierOrKeyword(precedingTrivia) End If Debug.Assert(Not IsNewLine(ch)) If fullWidth Then Debug.Assert(Not IsDoubleQuote(ch)) Return Nothing End If If IsDoubleQuote(ch) Then Return ScanStringLiteral(precedingTrivia) End If If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) Return ScanTokenFullWidth(precedingTrivia, ch) End If Return Nothing End Function ' at this point it is very likely that we are located at the beginning of a token Private Function TryScanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken If CanGet() Then Return ScanTokenCommon(precedingTrivia, Peek(), False) End If Return MakeEofToken(precedingTrivia) End Function Private Function ScanTokenFullWidth(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), ch As Char) As SyntaxToken Return ScanTokenCommon(precedingTrivia, ch, True) End Function ' // Allow whitespace between the characters of a two-character token. Private Function TrySkipFollowingEquals(ByRef index As Integer) As Boolean Debug.Assert(index > 0) Debug.Assert(CanGet(index - 1)) Dim here = index Dim eq As Char While CanGet(here) eq = Peek(here) here += 1 If Not IsWhitespace(eq) Then If eq = "="c OrElse eq = FULLWIDTH_EQUALS_SIGN Then index = here Return True Else Return False End If End If End While Return False End Function Private Function ScanRightAngleBracket(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As SyntaxToken Debug.Assert(CanGet) ' > Debug.Assert(Peek() = ">"c OrElse Peek() = FULLWIDTH_GREATER_THAN_SIGN) Dim length As Integer = 1 ' // Allow whitespace between the characters of a two-character token. length = GetWhitespaceLength(length) If CanGet(length) Then Dim c As Char = Peek(length) If c = "="c OrElse c = FULLWIDTH_EQUALS_SIGN Then length += 1 Return MakeGreaterThanEqualsToken(precedingTrivia, length) ElseIf c = ">"c OrElse c = FULLWIDTH_GREATER_THAN_SIGN Then length += 1 If TrySkipFollowingEquals(length) Then Return MakeGreaterThanGreaterThanEqualsToken(precedingTrivia, length) Else Return MakeGreaterThanGreaterThanToken(precedingTrivia, length) End If End If End If Return MakeGreaterThanToken(precedingTrivia, charIsFullWidth) End Function Private Function ScanLeftAngleBracket(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean, scanTrailingTrivia As ScanTriviaFunc) As SyntaxToken Debug.Assert(CanGet) ' < Debug.Assert(Peek() = "<"c OrElse Peek() = FULLWIDTH_LESS_THAN_SIGN) Dim length As Integer = 1 ' Check for XML tokens If Not charIsFullWidth AndAlso CanGet(length) Then Dim c As Char = Peek(length) Select Case c Case "!"c If CanGet(length + 2) Then Select Case (Peek(length + 1)) Case "-"c If CanGet(length + 3) AndAlso Peek(length + 2) = "-"c Then Return XmlMakeBeginCommentToken(precedingTrivia, scanTrailingTrivia) End If Case "["c If NextAre(length + 2, "CDATA[") Then Return XmlMakeBeginCDataToken(precedingTrivia, scanTrailingTrivia) End If End Select End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, scanTrailingTrivia) Case "/"c Return XmlMakeBeginEndElementToken(precedingTrivia, _scanSingleLineTriviaFunc) End Select End If ' // Allow whitespace between the characters of a two-character token. length = GetWhitespaceLength(length) If CanGet(length) Then Dim c As Char = Peek(length) If c = "="c OrElse c = FULLWIDTH_EQUALS_SIGN Then length += 1 Return MakeLessThanEqualsToken(precedingTrivia, length) ElseIf c = ">"c OrElse c = FULLWIDTH_GREATER_THAN_SIGN Then length += 1 Return MakeLessThanGreaterThanToken(precedingTrivia, length) ElseIf c = "<"c OrElse c = FULLWIDTH_LESS_THAN_SIGN Then length += 1 If CanGet(length) Then c = Peek(length) 'if the second "<" is a part of "<%" - like in "<<%" , we do not want to use it. If c <> "%"c AndAlso c <> FULLWIDTH_PERCENT_SIGN Then If TrySkipFollowingEquals(length) Then Return MakeLessThanLessThanEqualsToken(precedingTrivia, length) Else Return MakeLessThanLessThanToken(precedingTrivia, length) End If End If End If End If End If Return MakeLessThanToken(precedingTrivia, charIsFullWidth) End Function ''' <remarks> ''' Not intended for use in Expression Compiler scenarios. ''' </remarks> Friend Shared Function IsIdentifier(spelling As String) As Boolean Dim spellingLength As Integer = spelling.Length If spellingLength = 0 Then Return False End If Dim c = spelling(0) If SyntaxFacts.IsIdentifierStartCharacter(c) Then ' SPEC: ... Visual Basic identifiers conform to the Unicode Standard Annex 15 with one ' SPEC: exception: identifiers may begin with an underscore (connector) character. ' SPEC: If an identifier begins with an underscore, it must contain at least one other ' SPEC: valid identifier character to disambiguate it from a line continuation. If IsConnectorPunctuation(c) AndAlso spellingLength = 1 Then Return False End If For i = 1 To spellingLength - 1 If Not IsIdentifierPartCharacter(spelling(i)) Then Return False End If Next End If Return True End Function Private Function ScanIdentifierOrKeyword(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Debug.Assert(IsIdentifierStartCharacter(Peek)) Debug.Assert(PeekStartComment(0) = 0) ' comment should be handled by caller Dim ch = Peek() If CanGet(1) Then Dim ch1 = Peek(1) If IsConnectorPunctuation(ch) AndAlso Not IsIdentifierPartCharacter(ch1) Then Return MakeBadToken(precedingTrivia, 1, ERRID.ERR_ExpectedIdentifier) End If End If Dim len = 1 ' we know that the first char was good ' // The C++ compiler refuses to inline IsIdentifierCharacter, so the ' // < 128 test is inline here. (This loop gets a *lot* of traffic.) ' TODO: make sure we get good perf here While CanGet(len) ch = Peek(len) Dim code = Convert.ToUInt16(ch) If code < 128US AndAlso IsNarrowIdentifierCharacter(code) OrElse IsWideIdentifierCharacter(ch) Then len += 1 Else Exit While End If End While 'Check for a type character Dim TypeCharacter As TypeCharacter = TypeCharacter.None If CanGet(len) Then ch = Peek(len) FullWidthRepeat: Select Case ch Case "!"c ' // If the ! is followed by an identifier it is a dictionary lookup operator, not a type character. If CanGet(len + 1) Then Dim NextChar As Char = Peek(len + 1) If IsIdentifierStartCharacter(NextChar) OrElse MatchOneOrAnotherOrFullwidth(NextChar, "["c, "]"c) Then Exit Select End If End If TypeCharacter = TypeCharacter.Single 'typeChars.chType_sR4 len += 1 Case "#"c TypeCharacter = TypeCharacter.Double ' typeChars.chType_sR8 len += 1 Case "$"c TypeCharacter = TypeCharacter.String 'typeChars.chType_String len += 1 Case "%"c TypeCharacter = TypeCharacter.Integer ' typeChars.chType_sI4 len += 1 Case "&"c TypeCharacter = TypeCharacter.Long 'typeChars.chType_sI8 len += 1 Case "@"c TypeCharacter = TypeCharacter.Decimal 'chType_sDecimal len += 1 Case Else If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) GoTo FullWidthRepeat End If End Select End If Dim tokenType As SyntaxKind = SyntaxKind.IdentifierToken Dim contextualKind As SyntaxKind = SyntaxKind.IdentifierToken Dim spelling = GetText(len) Dim baseSpelling = If(TypeCharacter = TypeCharacter.None, spelling, Intern(spelling, 0, len - 1)) ' this can be keyword only if it has no type character, or if it is Mid$ If TypeCharacter = TypeCharacter.None Then tokenType = TokenOfStringCached(spelling) If SyntaxFacts.IsContextualKeyword(tokenType) Then contextualKind = tokenType tokenType = SyntaxKind.IdentifierToken End If ElseIf TokenOfStringCached(baseSpelling) = SyntaxKind.MidKeyword Then contextualKind = SyntaxKind.MidKeyword tokenType = SyntaxKind.IdentifierToken End If If tokenType <> SyntaxKind.IdentifierToken Then ' KEYWORD Return MakeKeyword(tokenType, spelling, precedingTrivia) Else ' IDENTIFIER or CONTEXTUAL Dim id As SyntaxToken = MakeIdentifier(spelling, contextualKind, False, baseSpelling, TypeCharacter, precedingTrivia) Return id End If End Function Private Function TokenOfStringCached(spelling As String) As SyntaxKind If spelling.Length > 16 Then Return SyntaxKind.IdentifierToken End If Return _KeywordsObjs.GetOrMakeValue(spelling) End Function Private Function ScanBracketedIdentifier(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) ' [ Debug.Assert(Peek() = "["c OrElse Peek() = FULLWIDTH_LEFT_SQUARE_BRACKET) Dim idStart As Integer = 1 Dim here As Integer = idStart Dim invalidIdentifier As Boolean = False If Not CanGet(here) Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_MissingEndBrack) End If Dim ch = Peek(here) ' check if we can start an ident. If Not IsIdentifierStartCharacter(ch) OrElse (IsConnectorPunctuation(ch) AndAlso Not (CanGet(here + 1) AndAlso IsIdentifierPartCharacter(Peek(here + 1)))) Then invalidIdentifier = True End If ' check ident until ] While CanGet(here) Dim [Next] As Char = Peek(here) If [Next] = "]"c OrElse [Next] = FULLWIDTH_RIGHT_SQUARE_BRACKET Then Dim idStringLength As Integer = here - idStart If idStringLength > 0 AndAlso Not invalidIdentifier Then Dim spelling = GetText(idStringLength + 2) ' TODO: this should be provable? Debug.Assert(spelling.Length > idStringLength + 1) ' TODO: consider interning. Dim baseText = spelling.Substring(1, idStringLength) Dim id As SyntaxToken = MakeIdentifier( spelling, SyntaxKind.IdentifierToken, True, baseText, TypeCharacter.None, precedingTrivia) Return id Else ' // The sequence "[]" does not define a valid identifier. Return MakeBadToken(precedingTrivia, here + 1, ERRID.ERR_ExpectedIdentifier) End If ElseIf IsNewLine([Next]) Then Exit While ElseIf Not IsIdentifierPartCharacter([Next]) Then invalidIdentifier = True Exit While End If here += 1 End While If here > 1 Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_MissingEndBrack) Else Return MakeBadToken(precedingTrivia, here, ERRID.ERR_ExpectedIdentifier) End If End Function Private Enum NumericLiteralKind Integral Float [Decimal] End Enum Private Function ScanNumericLiteral(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Dim here As Integer = 0 Dim integerLiteralStart As Integer Dim UnderscoreInWrongPlace As Boolean Dim UnderscoreUsed As Boolean = False Dim LeadingUnderscoreUsed = False Dim base As LiteralBase = LiteralBase.Decimal Dim literalKind As NumericLiteralKind = NumericLiteralKind.Integral ' #################################################### ' // Validate literal and find where the number starts and ends. ' #################################################### ' // First read a leading base specifier, if present, followed by a sequence of zero ' // or more digits. Dim ch = Peek() If ch = "&"c OrElse ch = FULLWIDTH_AMPERSAND Then here += 1 ch = If(CanGet(here), Peek(here), ChrW(0)) FullWidthRepeat: Select Case ch Case "H"c, "h"c here += 1 integerLiteralStart = here base = LiteralBase.Hexadecimal If CanGet(here) AndAlso Peek(here) = "_"c Then LeadingUnderscoreUsed = True End If While CanGet(here) ch = Peek(here) If Not IsHexDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Case "B"c, "b"c here += 1 integerLiteralStart = here base = LiteralBase.Binary If CanGet(here) AndAlso Peek(here) = "_"c Then LeadingUnderscoreUsed = True End If While CanGet(here) ch = Peek(here) If Not IsBinaryDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Case "O"c, "o"c here += 1 integerLiteralStart = here base = LiteralBase.Octal If CanGet(here) AndAlso Peek(here) = "_"c Then LeadingUnderscoreUsed = True End If While CanGet(here) ch = Peek(here) If Not IsOctalDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Case Else If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) GoTo FullWidthRepeat End If Throw ExceptionUtilities.UnexpectedValue(ch) End Select Else ' no base specifier - just go through decimal digits. integerLiteralStart = here UnderscoreInWrongPlace = (CanGet(here) AndAlso Peek(here) = "_"c) While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While If here <> integerLiteralStart Then UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) End If End If ' we may have a dot, and then it is a float, but if this is an integral, then we have seen it all. Dim integerLiteralEnd As Integer = here ' // Unless there was an explicit base specifier (which indicates an integer literal), ' // read the rest of a float literal. If base = LiteralBase.Decimal AndAlso CanGet(here) Then ' // First read a '.' followed by a sequence of one or more digits. ch = Peek(here) If (ch = "."c Or ch = FULLWIDTH_FULL_STOP) AndAlso CanGet(here + 1) AndAlso IsDecimalDigit(Peek(here + 1)) Then here += 2 ' skip dot and first digit ' all following decimal digits belong to the literal (fractional part) While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) AndAlso ch <> "_"c Then Exit While End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) literalKind = NumericLiteralKind.Float End If ' // Read an exponent symbol followed by an optional sign and a sequence of ' // one or more digits. If CanGet(here) AndAlso BeginsExponent(Peek(here)) Then here += 1 If CanGet(here) Then ch = Peek(here) If MatchOneOrAnotherOrFullwidth(ch, "+"c, "-"c) Then here += 1 End If End If If CanGet(here) AndAlso IsDecimalDigit(Peek(here)) Then here += 1 While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) AndAlso ch <> "_"c Then Exit While End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Else Return MakeBadToken(precedingTrivia, here, ERRID.ERR_InvalidLiteralExponent) End If literalKind = NumericLiteralKind.Float End If End If Dim literalWithoutTypeChar = here ' #################################################### ' // Read a trailing type character. ' #################################################### Dim TypeCharacter As TypeCharacter = TypeCharacter.None If CanGet(here) Then ch = Peek(here) FullWidthRepeat2: Select Case ch Case "!"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.Single literalKind = NumericLiteralKind.Float here += 1 End If Case "F"c, "f"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.SingleLiteral literalKind = NumericLiteralKind.Float here += 1 End If Case "#"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.Double literalKind = NumericLiteralKind.Float here += 1 End If Case "R"c, "r"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.DoubleLiteral literalKind = NumericLiteralKind.Float here += 1 End If Case "S"c, "s"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.ShortLiteral here += 1 End If Case "%"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.Integer here += 1 End If Case "I"c, "i"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.IntegerLiteral here += 1 End If Case "&"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.Long here += 1 End If Case "L"c, "l"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.LongLiteral here += 1 End If Case "@"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.Decimal literalKind = NumericLiteralKind.Decimal here += 1 End If Case "D"c, "d"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.DecimalLiteral literalKind = NumericLiteralKind.Decimal ' check if this was not attempt to use obsolete exponent If CanGet(here + 1) Then ch = Peek(here + 1) If IsDecimalDigit(ch) OrElse MatchOneOrAnotherOrFullwidth(ch, "+"c, "-"c) Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_ObsoleteExponent) End If End If here += 1 End If Case "U"c, "u"c If literalKind <> NumericLiteralKind.Float AndAlso CanGet(here + 1) Then Dim NextChar As Char = Peek(here + 1) 'unsigned suffixes - US, UL, UI If MatchOneOrAnotherOrFullwidth(NextChar, "S"c, "s"c) Then TypeCharacter = TypeCharacter.UShortLiteral here += 2 ElseIf MatchOneOrAnotherOrFullwidth(NextChar, "I"c, "i"c) Then TypeCharacter = TypeCharacter.UIntegerLiteral here += 2 ElseIf MatchOneOrAnotherOrFullwidth(NextChar, "L"c, "l"c) Then TypeCharacter = TypeCharacter.ULongLiteral here += 2 End If End If Case Else If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) GoTo FullWidthRepeat2 End If End Select End If ' #################################################### ' // Produce a value for the literal. ' #################################################### Dim integralValue As UInt64 Dim floatingValue As Double Dim decimalValue As Decimal Dim Overflows As Boolean = False If literalKind = NumericLiteralKind.Integral Then If integerLiteralStart = integerLiteralEnd Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_Syntax) Else integralValue = 0 If base = LiteralBase.Decimal Then ' Init For loop For LiteralCharacter As Integer = integerLiteralStart To integerLiteralEnd - 1 Dim LiteralCharacterValue As Char = Peek(LiteralCharacter) If LiteralCharacterValue = "_"c Then Continue For End If Dim NextCharacterValue As UInteger = IntegralLiteralCharacterValue(LiteralCharacterValue) If integralValue < 1844674407370955161UL OrElse (integralValue = 1844674407370955161UL AndAlso NextCharacterValue <= 5UI) Then integralValue = (integralValue * 10UL) + NextCharacterValue Else Overflows = True Exit For End If Next If TypeCharacter <> TypeCharacter.ULongLiteral AndAlso integralValue > Long.MaxValue Then Overflows = True End If Else Dim Shift As Integer = If(base = LiteralBase.Hexadecimal, 4, If(Base = LiteralBase.Octal, 3, 1)) Dim OverflowMask As UInt64 = If(base = LiteralBase.Hexadecimal, &HF000000000000000UL, If(base = LiteralBase.Octal, &HE000000000000000UL, &H8000000000000000UL)) ' Init For loop For LiteralCharacter As Integer = integerLiteralStart To integerLiteralEnd - 1 Dim LiteralCharacterValue As Char = Peek(LiteralCharacter) If LiteralCharacterValue = "_"c Then Continue For End If If (integralValue And OverflowMask) <> 0 Then Overflows = True End If integralValue = (integralValue << Shift) + IntegralLiteralCharacterValue(LiteralCharacterValue) Next End If If TypeCharacter = TypeCharacter.None Then ' nothing to do ElseIf TypeCharacter = TypeCharacter.Integer OrElse TypeCharacter = TypeCharacter.IntegerLiteral Then If (base = LiteralBase.Decimal AndAlso integralValue > &H7FFFFFFF) OrElse integralValue > &HFFFFFFFFUI Then Overflows = True End If ElseIf TypeCharacter = TypeCharacter.UIntegerLiteral Then If integralValue > &HFFFFFFFFUI Then Overflows = True End If ElseIf TypeCharacter = TypeCharacter.ShortLiteral Then If (base = LiteralBase.Decimal AndAlso integralValue > &H7FFF) OrElse integralValue > &HFFFF Then Overflows = True End If ElseIf TypeCharacter = TypeCharacter.UShortLiteral Then If integralValue > &HFFFF Then Overflows = True End If Else Debug.Assert(TypeCharacter = TypeCharacter.Long OrElse TypeCharacter = TypeCharacter.LongLiteral OrElse TypeCharacter = TypeCharacter.ULongLiteral, "Integral literal value computation is lost.") End If End If Else ' // Copy the text of the literal to deal with fullwidth Dim scratch = GetScratch() For i = 0 To literalWithoutTypeChar - 1 Dim curCh = Peek(i) If curCh <> "_"c Then scratch.Append(If(IsFullWidth(curCh), MakeHalfWidth(curCh), curCh)) End If Next Dim LiteralSpelling = GetScratchTextInterned(scratch) If literalKind = NumericLiteralKind.Decimal Then ' Attempt to convert to Decimal. Overflows = Not GetDecimalValue(LiteralSpelling, decimalValue) Else If TypeCharacter = TypeCharacter.Single OrElse TypeCharacter = TypeCharacter.SingleLiteral Then ' // Attempt to convert to single Dim SingleValue As Single If Not RealParser.TryParseFloat(LiteralSpelling, SingleValue) Then Overflows = True Else floatingValue = SingleValue End If Else ' // Attempt to convert to double. If Not RealParser.TryParseDouble(LiteralSpelling, floatingValue) Then Overflows = True End If End If End If End If Dim result As SyntaxToken Select Case literalKind Case NumericLiteralKind.Integral result = MakeIntegerLiteralToken(precedingTrivia, base, TypeCharacter, If(Overflows Or UnderscoreInWrongPlace, 0UL, IntegralValue), here) Case NumericLiteralKind.Float result = MakeFloatingLiteralToken(precedingTrivia, TypeCharacter, If(Overflows Or UnderscoreInWrongPlace, 0.0F, floatingValue), here) Case NumericLiteralKind.Decimal result = MakeDecimalLiteralToken(precedingTrivia, TypeCharacter, If(Overflows Or UnderscoreInWrongPlace, 0D, decimalValue), here) Case Else Throw ExceptionUtilities.UnexpectedValue(literalKind) End Select If Overflows Then result = DirectCast(result.AddError(ErrorFactory.ErrorInfo(ERRID.ERR_Overflow)), SyntaxToken) End If If UnderscoreInWrongPlace Then result = DirectCast(result.AddError(ErrorFactory.ErrorInfo(ERRID.ERR_Syntax)), SyntaxToken) ElseIf LeadingUnderscoreUsed Then result = CheckFeatureAvailability(result, Feature.LeadingDigitSeparator) ElseIf UnderscoreUsed Then result = CheckFeatureAvailability(result, Feature.DigitSeparators) End If If base = LiteralBase.Binary Then result = CheckFeatureAvailability(result, Feature.BinaryLiterals) End If Return result End Function Private Shared Function GetDecimalValue(text As String, <Out()> ByRef value As Decimal) As Boolean ' Use Decimal.TryParse to parse value. Note: the behavior of ' Decimal.TryParse differs from Dev11 in the following cases: ' ' 1. [-]0eNd where N > 0 ' The native compiler ignores sign and scale and treats such cases ' as 0e0d. Decimal.TryParse fails so these cases are compile errors. ' [Bug #568475] ' 2. Decimals with significant digits below 1e-49 ' The native compiler considers digits below 1e-49 when rounding. ' Decimal.TryParse ignores digits below 1e-49 when rounding. This ' difference is perhaps the most significant since existing code will ' continue to compile but constant values may be rounded differently. ' [Bug #568494] Return Decimal.TryParse(text, NumberStyles.AllowDecimalPoint Or NumberStyles.AllowExponent, CultureInfo.InvariantCulture, value) End Function Private Function ScanIntLiteral( ByRef ReturnValue As Integer, ByRef here As Integer ) As Boolean Debug.Assert(here >= 0) If Not CanGet(here) Then Return False End If Dim ch = Peek(here) If Not IsDecimalDigit(ch) Then Return False End If Dim integralValue As Integer = IntegralLiteralCharacterValue(ch) here += 1 While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) Then Exit While End If Dim nextDigit = IntegralLiteralCharacterValue(ch) If integralValue < 214748364 OrElse (integralValue = 214748364 AndAlso nextDigit < 8) Then integralValue = integralValue * 10 + nextDigit here += 1 Else Return False End If End While ReturnValue = integralValue Return True End Function Private Function ScanDateLiteral(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Debug.Assert(IsHash(Peek())) Dim here As Integer = 1 'skip # Dim firstValue As Integer Dim YearValue, MonthValue, DayValue, HourValue, MinuteValue, SecondValue As Integer Dim haveDateValue As Boolean = False Dim haveYearValue As Boolean = False Dim haveTimeValue As Boolean = False Dim haveMinuteValue As Boolean = False Dim haveSecondValue As Boolean = False Dim haveAM As Boolean = False Dim havePM As Boolean = False Dim dateIsInvalid As Boolean = False Dim YearIsTwoDigits As Boolean = False Dim daysToMonth As Integer() = Nothing Dim yearIsFirst As Boolean = False ' // Unfortunately, we can't fall back on OLE Automation's date parsing because ' // they don't have the same range as the URT's DateTime class ' // First, eat any whitespace here = GetWhitespaceLength(here) Dim firstValueStart As Integer = here ' // The first thing has to be an integer, although it's not clear what it is yet If Not ScanIntLiteral(firstValue, here) Then Return Nothing End If ' // If we see a /, then it's a date If CanGet(here) AndAlso IsDateSeparatorCharacter(Peek(here)) Then Dim FirstDateSeparator As Integer = here ' // We've got a date haveDateValue = True here += 1 ' Is the first value a year? ' It is a year if it consists of exactly 4 digits. ' Condition below uses 5 because we already skipped the separator. If here - firstValueStart = 5 Then haveYearValue = True yearIsFirst = True YearValue = firstValue ' // We have to have a month value If Not ScanIntLiteral(MonthValue, here) Then GoTo baddate End If ' Do we have a day value? If CanGet(here) AndAlso IsDateSeparatorCharacter(Peek(here)) Then ' // Check to see they used a consistent separator If Peek(here) <> Peek(FirstDateSeparator) Then GoTo baddate End If ' // Yes. here += 1 If Not ScanIntLiteral(DayValue, here) Then GoTo baddate End If End If Else ' First value is month MonthValue = firstValue ' // We have to have a day value If Not ScanIntLiteral(DayValue, here) Then GoTo baddate End If ' // Do we have a year value? If CanGet(here) AndAlso IsDateSeparatorCharacter(Peek(here)) Then ' // Check to see they used a consistent separator If Peek(here) <> Peek(FirstDateSeparator) Then GoTo baddate End If ' // Yes. haveYearValue = True here += 1 Dim YearStart As Integer = here If Not ScanIntLiteral(YearValue, here) Then GoTo baddate End If If (here - YearStart) = 2 Then YearIsTwoDigits = True End If End If End If here = GetWhitespaceLength(here) End If ' // If we haven't seen a date, assume it's a time value If Not haveDateValue Then haveTimeValue = True HourValue = firstValue Else ' // We did see a date. See if we see a time value... If ScanIntLiteral(HourValue, here) Then ' // Yup. haveTimeValue = True End If End If If haveTimeValue Then ' // Do we see a :? If CanGet(here) AndAlso IsColon(Peek(here)) Then here += 1 ' // Now let's get the minute value If Not ScanIntLiteral(MinuteValue, here) Then GoTo baddate End If haveMinuteValue = True ' // Do we have a second value? If CanGet(here) AndAlso IsColon(Peek(here)) Then ' // Yes. haveSecondValue = True here += 1 If Not ScanIntLiteral(SecondValue, here) Then GoTo baddate End If End If End If here = GetWhitespaceLength(here) ' // Check AM/PM If CanGet(here) Then If Peek(here) = "A"c OrElse Peek(here) = FULLWIDTH_LATIN_CAPITAL_LETTER_A OrElse Peek(here) = "a"c OrElse Peek(here) = FULLWIDTH_LATIN_SMALL_LETTER_A Then haveAM = True here += 1 ElseIf Peek(here) = "P"c OrElse Peek(here) = FULLWIDTH_LATIN_CAPITAL_LETTER_P OrElse Peek(here) = "p"c OrElse Peek(here) = FULLWIDTH_LATIN_SMALL_LETTER_P Then havePM = True here += 1 End If If CanGet(here) AndAlso (haveAM OrElse havePM) Then If Peek(here) = "M"c OrElse Peek(here) = FULLWIDTH_LATIN_CAPITAL_LETTER_M OrElse Peek(here) = "m"c OrElse Peek(here) = FULLWIDTH_LATIN_SMALL_LETTER_M Then here = GetWhitespaceLength(here + 1) Else GoTo baddate End If End If End If ' // If there's no minute/second value and no AM/PM, it's invalid If Not haveMinuteValue AndAlso Not haveAM AndAlso Not havePM Then GoTo baddate End If End If If Not CanGet(here) OrElse Not IsHash(Peek(here)) Then GoTo baddate End If here += 1 ' // OK, now we've got all the values, let's see if we've got a valid date If haveDateValue Then If MonthValue < 1 OrElse MonthValue > 12 Then dateIsInvalid = True End If ' // We'll check Days in a moment... If Not haveYearValue Then dateIsInvalid = True YearValue = 1 End If ' // Check if not a leap year If Not ((YearValue Mod 4 = 0) AndAlso (Not (YearValue Mod 100 = 0) OrElse (YearValue Mod 400 = 0))) Then daysToMonth = DaysToMonth365 Else daysToMonth = DaysToMonth366 End If If DayValue < 1 OrElse (Not dateIsInvalid AndAlso DayValue > daysToMonth(MonthValue) - daysToMonth(MonthValue - 1)) Then dateIsInvalid = True End If If YearIsTwoDigits Then dateIsInvalid = True End If If YearValue < 1 OrElse YearValue > 9999 Then dateIsInvalid = True End If Else MonthValue = 1 DayValue = 1 YearValue = 1 daysToMonth = DaysToMonth365 End If If haveTimeValue Then If haveAM OrElse havePM Then ' // 12-hour value If HourValue < 1 OrElse HourValue > 12 Then dateIsInvalid = True End If If haveAM Then HourValue = HourValue Mod 12 ElseIf havePM Then HourValue = HourValue + 12 If HourValue = 24 Then HourValue = 12 End If End If Else If HourValue < 0 OrElse HourValue > 23 Then dateIsInvalid = True End If End If If haveMinuteValue Then If MinuteValue < 0 OrElse MinuteValue > 59 Then dateIsInvalid = True End If Else MinuteValue = 0 End If If haveSecondValue Then If SecondValue < 0 OrElse SecondValue > 59 Then dateIsInvalid = True End If Else SecondValue = 0 End If Else HourValue = 0 MinuteValue = 0 SecondValue = 0 End If ' // Ok, we've got a valid value. Now make into an i8. If Not dateIsInvalid Then Dim DateTimeValue As New DateTime(YearValue, MonthValue, DayValue, HourValue, MinuteValue, SecondValue) Dim result = MakeDateLiteralToken(precedingTrivia, DateTimeValue, here) If yearIsFirst Then result = Parser.CheckFeatureAvailability(Feature.YearFirstDateLiterals, result, Options.LanguageVersion) End If Return result Else Return MakeBadToken(precedingTrivia, here, ERRID.ERR_InvalidDate) End If baddate: ' // If we can find a closing #, then assume it's a malformed date, ' // otherwise, it's not a date While CanGet(here) Dim ch As Char = Peek(here) If IsHash(ch) OrElse IsNewLine(ch) Then Exit While End If here += 1 End While If Not CanGet(here) OrElse IsNewLine(Peek(here)) Then ' // No closing # Return Nothing Else Debug.Assert(IsHash(Peek(here))) here += 1 ' consume trailing # Return MakeBadToken(precedingTrivia, here, ERRID.ERR_InvalidDate) End If End Function Private Function ScanStringLiteral(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Debug.Assert(IsDoubleQuote(Peek)) Dim length As Integer = 1 Dim ch As Char Dim followingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) ' // Check for a Char literal, which can be of the form: ' // """"c or "<anycharacter-except-">"c If CanGet(3) AndAlso IsDoubleQuote(Peek(2)) Then If IsDoubleQuote(Peek(1)) Then If IsDoubleQuote(Peek(3)) AndAlso CanGet(4) AndAlso IsLetterC(Peek(4)) Then ' // Double-quote Char literal: """"c Return MakeCharacterLiteralToken(precedingTrivia, """"c, 5) End If ElseIf IsLetterC(Peek(3)) Then ' // Char literal. "x"c Return MakeCharacterLiteralToken(precedingTrivia, Peek(1), 4) End If End If If CanGet(2) AndAlso IsDoubleQuote(Peek(1)) AndAlso IsLetterC(Peek(2)) Then ' // Error. ""c is not a legal char constant Return MakeBadToken(precedingTrivia, 3, ERRID.ERR_IllegalCharConstant) End If Dim haveNewLine As Boolean = False Dim scratch = GetScratch() While CanGet(length) ch = Peek(length) If IsDoubleQuote(ch) Then If CanGet(length + 1) Then ch = Peek(length + 1) If IsDoubleQuote(ch) Then ' // An escaped double quote scratch.Append(""""c) length += 2 Continue While Else ' // The end of the char literal. If IsLetterC(ch) Then ' // Error. "aad"c is not a legal char constant ' // +2 to include both " and c in the token span scratch.Clear() Return MakeBadToken(precedingTrivia, length + 2, ERRID.ERR_IllegalCharConstant) End If End If End If ' the double quote was a valid string terminator. length += 1 Dim spelling = GetTextNotInterned(length) followingTrivia = ScanSingleLineTrivia() ' NATURAL TEXT, NO INTERNING Dim result As SyntaxToken = SyntaxFactory.StringLiteralToken(spelling, GetScratchText(scratch), precedingTrivia.Node, followingTrivia.Node) If haveNewLine Then result = Parser.CheckFeatureAvailability(Feature.MultilineStringLiterals, result, Options.LanguageVersion) End If Return result ElseIf IsNewLine(ch) Then If _isScanningDirective Then Exit While End If haveNewLine = True End If scratch.Append(ch) length += 1 End While ' CC has trouble to prove this after the loop Debug.Assert(CanGet(length - 1)) '// The literal does not have an explicit termination. ' DIFFERENT: here in IDE we used to report string token marked as unterminated Dim sp = GetTextNotInterned(length) followingTrivia = ScanSingleLineTrivia() Dim strTk = SyntaxFactory.StringLiteralToken(sp, GetScratchText(scratch), precedingTrivia.Node, followingTrivia.Node) Dim StrTkErr = strTk.SetDiagnostics({ErrorFactory.ErrorInfo(ERRID.ERR_UnterminatedStringLiteral)}) Debug.Assert(StrTkErr IsNot Nothing) Return DirectCast(StrTkErr, SyntaxToken) End Function Friend Shared Function TryIdentifierAsContextualKeyword(id As IdentifierTokenSyntax, ByRef k As SyntaxKind) As Boolean Debug.Assert(id IsNot Nothing) If id.PossibleKeywordKind <> SyntaxKind.IdentifierToken Then k = id.PossibleKeywordKind Return True End If Return False End Function ''' <summary> ''' Try to convert an Identifier to a Keyword. Called by the parser when it wants to force ''' an identifier to be a keyword. ''' </summary> Friend Function TryIdentifierAsContextualKeyword(id As IdentifierTokenSyntax, ByRef k As KeywordSyntax) As Boolean Debug.Assert(id IsNot Nothing) Dim kind As SyntaxKind = SyntaxKind.IdentifierToken If TryIdentifierAsContextualKeyword(id, kind) Then k = MakeKeyword(id) Return True End If Return False End Function Friend Function TryTokenAsContextualKeyword(t As SyntaxToken, ByRef k As KeywordSyntax) As Boolean If t Is Nothing Then Return False End If If t.Kind = SyntaxKind.IdentifierToken Then Return TryIdentifierAsContextualKeyword(DirectCast(t, IdentifierTokenSyntax), k) End If Return False End Function Friend Shared Function TryTokenAsKeyword(t As SyntaxToken, ByRef kind As SyntaxKind) As Boolean If t Is Nothing Then Return False End If If t.IsKeyword Then kind = t.Kind Return True End If If t.Kind = SyntaxKind.IdentifierToken Then Return TryIdentifierAsContextualKeyword(DirectCast(t, IdentifierTokenSyntax), kind) End If Return False End Function Friend Shared Function IsContextualKeyword(t As SyntaxToken, ParamArray kinds As SyntaxKind()) As Boolean Dim kind As SyntaxKind = Nothing If TryTokenAsKeyword(t, kind) Then Return Array.IndexOf(kinds, kind) >= 0 End If Return False End Function Private Function IsIdentifierStartCharacter(c As Char) As Boolean Return (_isScanningForExpressionCompiler AndAlso c = "$"c) OrElse SyntaxFacts.IsIdentifierStartCharacter(c) End Function Private Function CheckFeatureAvailability(token As SyntaxToken, feature As Feature) As SyntaxToken If CheckFeatureAvailability(feature) Then Return token End If Dim requiredVersion = New VisualBasicRequiredLanguageVersion(feature.GetLanguageVersion()) Dim errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_LanguageVersion, _options.LanguageVersion.GetErrorName(), ErrorFactory.ErrorInfo(feature.GetResourceId()), requiredVersion) Return DirectCast(token.AddError(errorInfo), SyntaxToken) End Function Friend Function CheckFeatureAvailability(feature As Feature) As Boolean Return CheckFeatureAvailability(Me.Options, feature) End Function Private Shared Function CheckFeatureAvailability(parseOptions As VisualBasicParseOptions, feature As Feature) As Boolean Dim featureFlag = feature.GetFeatureFlag() If featureFlag IsNot Nothing Then Return parseOptions.Features.ContainsKey(featureFlag) End If Dim required = feature.GetLanguageVersion() Dim actual = parseOptions.LanguageVersion Return CInt(required) <= CInt(actual) End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. '----------------------------------------------------------------------------- ' Contains the definition of the Scanner, which produces tokens from text '----------------------------------------------------------------------------- Option Compare Binary Option Strict On Imports System.Collections.Immutable Imports System.Globalization Imports System.Runtime.InteropServices Imports System.Text Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.SyntaxFacts Imports Microsoft.CodeAnalysis.Collections Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax Imports CoreInternalSyntax = Microsoft.CodeAnalysis.Syntax.InternalSyntax Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax ''' <summary> ''' Creates red tokens for a stream of text ''' </summary> Friend Class Scanner Implements IDisposable Private Delegate Function ScanTriviaFunc() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Private Shared ReadOnly s_scanNoTriviaFunc As ScanTriviaFunc = Function() Nothing Private ReadOnly _scanSingleLineTriviaFunc As ScanTriviaFunc = AddressOf ScanSingleLineTrivia Protected _lineBufferOffset As Integer ' marks the next character to read from _buffer Private _endOfTerminatorTrivia As Integer ' marks how far scanner may have scanned ahead for terminator trivia. This may be greater than _lineBufferOffset Friend Const BadTokenCountLimit As Integer = 200 Private _badTokenCount As Integer ' cumulative count of bad tokens produced Private ReadOnly _sbPooled As PooledStringBuilder = PooledStringBuilder.GetInstance ''' <summary> ''' DO NOT USE DIRECTLY. ''' USE GetScratch() ''' </summary> Private ReadOnly _sb As StringBuilder = _sbPooled.Builder Private ReadOnly _triviaListPool As New SyntaxListPool Private ReadOnly _options As VisualBasicParseOptions Private ReadOnly _stringTable As StringTable = StringTable.GetInstance() Private ReadOnly _quickTokenTable As TextKeyedCache(Of SyntaxToken) = TextKeyedCache(Of SyntaxToken).GetInstance Public Const TABLE_LIMIT = 512 Private Shared ReadOnly s_keywordKindFactory As Func(Of String, SyntaxKind) = Function(spelling) KeywordTable.TokenOfString(spelling) Private Shared ReadOnly s_keywordsObjsPool As ObjectPool(Of CachingIdentityFactory(Of String, SyntaxKind)) = CachingIdentityFactory(Of String, SyntaxKind).CreatePool(TABLE_LIMIT, s_keywordKindFactory) Private ReadOnly _KeywordsObjs As CachingIdentityFactory(Of String, SyntaxKind) = s_keywordsObjsPool.Allocate() Private Shared ReadOnly s_idTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, IdentifierTokenSyntax))( Function() New CachingFactory(Of TokenParts, IdentifierTokenSyntax)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _idTable As CachingFactory(Of TokenParts, IdentifierTokenSyntax) = s_idTablePool.Allocate() Private Shared ReadOnly s_kwTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, KeywordSyntax))( Function() New CachingFactory(Of TokenParts, KeywordSyntax)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _kwTable As CachingFactory(Of TokenParts, KeywordSyntax) = s_kwTablePool.Allocate Private Shared ReadOnly s_punctTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, PunctuationSyntax))( Function() New CachingFactory(Of TokenParts, PunctuationSyntax)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _punctTable As CachingFactory(Of TokenParts, PunctuationSyntax) = s_punctTablePool.Allocate() Private Shared ReadOnly s_literalTablePool As New ObjectPool(Of CachingFactory(Of TokenParts, SyntaxToken))( Function() New CachingFactory(Of TokenParts, SyntaxToken)(TABLE_LIMIT, Nothing, s_tokenKeyHasher, s_tokenKeyEquality)) Private ReadOnly _literalTable As CachingFactory(Of TokenParts, SyntaxToken) = s_literalTablePool.Allocate Private Shared ReadOnly s_wslTablePool As New ObjectPool(Of CachingFactory(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)))( Function() New CachingFactory(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode))(TABLE_LIMIT, s_wsListFactory, s_wsListKeyHasher, s_wsListKeyEquality)) Private ReadOnly _wslTable As CachingFactory(Of SyntaxListBuilder, CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) = s_wslTablePool.Allocate Private Shared ReadOnly s_wsTablePool As New ObjectPool(Of CachingFactory(Of TriviaKey, SyntaxTrivia))( Function() CreateWsTable()) Private ReadOnly _wsTable As CachingFactory(Of TriviaKey, SyntaxTrivia) = s_wsTablePool.Allocate Private ReadOnly _isScanningForExpressionCompiler As Boolean Private _isDisposed As Boolean Private Function GetScratch() As StringBuilder ' the normal pattern is that we clean scratch after use. ' hitting this assert very likely indicates that you ' did not release scratch content or worse trying to use ' scratch in two places at a time. Debug.Assert(_sb.Length = 0, "trying to use dirty buffer?") Return _sb End Function #Region "Public interface" Friend Sub New(textToScan As SourceText, options As VisualBasicParseOptions, Optional isScanningForExpressionCompiler As Boolean = False) Debug.Assert(textToScan IsNot Nothing) _lineBufferOffset = 0 _buffer = textToScan _bufferLen = textToScan.Length _curPage = GetPage(0) _options = options _scannerPreprocessorState = New PreprocessorState(GetPreprocessorConstants(options)) _isScanningForExpressionCompiler = isScanningForExpressionCompiler End Sub Friend Sub Dispose() Implements IDisposable.Dispose If Not _isDisposed Then _isDisposed = True _KeywordsObjs.Free() _quickTokenTable.Free() _stringTable.Free() _sbPooled.Free() s_idTablePool.Free(_idTable) s_kwTablePool.Free(_kwTable) s_punctTablePool.Free(_punctTable) s_literalTablePool.Free(_literalTable) s_wslTablePool.Free(_wslTable) s_wsTablePool.Free(_wsTable) For Each p As Page In _pages If p IsNot Nothing Then p.Free() End If Next Array.Clear(_pages, 0, _pages.Length) End If End Sub Friend ReadOnly Property Options As VisualBasicParseOptions Get Return _options End Get End Property Friend Shared Function GetPreprocessorConstants(options As VisualBasicParseOptions) As ImmutableDictionary(Of String, CConst) If options.PreprocessorSymbols.IsDefaultOrEmpty Then Return ImmutableDictionary(Of String, CConst).Empty End If Dim result = ImmutableDictionary.CreateBuilder(Of String, CConst)(IdentifierComparison.Comparer) For Each symbol In options.PreprocessorSymbols ' The values in options have already been verified result(symbol.Key) = CConst.CreateChecked(symbol.Value) Next Return result.ToImmutable() End Function Private Function GetNextToken(Optional allowLeadingMultilineTrivia As Boolean = False) As SyntaxToken ' Use quick token scanning to see if we can scan a token quickly. Dim quickToken = QuickScanToken(allowLeadingMultilineTrivia) If quickToken.Succeeded Then Dim token = _quickTokenTable.FindItem(quickToken.Chars, quickToken.Start, quickToken.Length, quickToken.HashCode) If token IsNot Nothing Then AdvanceChar(quickToken.Length) If quickToken.TerminatorLength <> 0 Then _endOfTerminatorTrivia = _lineBufferOffset _lineBufferOffset -= quickToken.TerminatorLength End If Return token End If End If Dim scannedToken = ScanNextToken(allowLeadingMultilineTrivia) ' If we quick-scanned a token, but didn't have a actual token cached for it, cache the token we created ' from the regular scanner. If quickToken.Succeeded Then Debug.Assert(quickToken.Length = scannedToken.FullWidth) _quickTokenTable.AddItem(quickToken.Chars, quickToken.Start, quickToken.Length, quickToken.HashCode, scannedToken) End If Return scannedToken End Function Private Function ScanNextToken(allowLeadingMultilineTrivia As Boolean) As SyntaxToken #If DEBUG Then Dim oldOffset = _lineBufferOffset #End If Dim leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) If allowLeadingMultilineTrivia Then leadingTrivia = ScanMultilineTrivia() Else leadingTrivia = ScanLeadingTrivia() ' Special case where the remainder of the line is a comment. Dim length = PeekStartComment(0) If length > 0 Then Return MakeEmptyToken(leadingTrivia) End If End If Dim token = TryScanToken(leadingTrivia) If token Is Nothing Then token = ScanNextCharAsToken(leadingTrivia) End If If _lineBufferOffset > _endOfTerminatorTrivia Then _endOfTerminatorTrivia = _lineBufferOffset End If #If DEBUG Then ' we must always consume as much as returned token's full length or things will go very bad Debug.Assert(oldOffset + token.FullWidth = _lineBufferOffset OrElse oldOffset + token.FullWidth = _endOfTerminatorTrivia OrElse token.FullWidth = 0) #End If Return token End Function Private Function ScanNextCharAsToken(leadingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Dim token As SyntaxToken If Not CanGet() Then token = MakeEofToken(leadingTrivia) Else _badTokenCount += 1 If _badTokenCount < BadTokenCountLimit Then ' // Don't break up surrogate pairs Dim c = Peek() Dim length = If(IsHighSurrogate(c) AndAlso CanGet(1) AndAlso IsLowSurrogate(Peek(1)), 2, 1) token = MakeBadToken(leadingTrivia, length, ERRID.ERR_IllegalChar) Else ' If we get too many characters that we cannot make sense of, absorb the rest of the input. token = MakeBadToken(leadingTrivia, RemainingLength(), ERRID.ERR_IllegalChar) End If End If Return token End Function ' // SkipToNextConditionalLine advances through the input stream until it finds a (logical) ' // line that has a '#' character as its first non-whitespace, non-continuation character. ' // SkipToNextConditionalLine ignores explicit line continuation. ' TODO: this could be vastly simplified if we could ignore line continuations. Public Function SkipToNextConditionalLine() As TextSpan ' start at current token ResetLineBufferOffset() Dim start = _lineBufferOffset ' if starting not from line start, skip to the next one. Dim prev = PrevToken If Not IsAtNewLine() OrElse (PrevToken IsNot Nothing AndAlso PrevToken.EndsWithEndOfLineOrColonTrivia) Then EatThroughLine() End If Dim condLineStart = _lineBufferOffset While (CanGet()) Dim c As Char = Peek() Select Case (c) Case CARRIAGE_RETURN, LINE_FEED EatThroughLineBreak(c) condLineStart = _lineBufferOffset Continue While Case SPACE, CHARACTER_TABULATION Debug.Assert(IsWhitespace(Peek())) EatWhitespace() Continue While Case _ "a"c, "b"c, "c"c, "d"c, "e"c, "f"c, "g"c, "h"c, "i"c, "j"c, "k"c, "l"c, "m"c, "n"c, "o"c, "p"c, "q"c, "r"c, "s"c, "t"c, "u"c, "v"c, "w"c, "x"c, "y"c, "z"c, "A"c, "B"c, "C"c, "D"c, "E"c, "F"c, "G"c, "H"c, "I"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c, "'"c, "_"c EatThroughLine() condLineStart = _lineBufferOffset Continue While Case "#"c, FULLWIDTH_NUMBER_SIGN Exit While Case Else If IsWhitespace(c) Then EatWhitespace() Continue While ElseIf IsNewLine(c) Then EatThroughLineBreak(c) condLineStart = _lineBufferOffset Continue While End If EatThroughLine() condLineStart = _lineBufferOffset Continue While End Select End While ' we did not find # or we have hit EoF. _lineBufferOffset = condLineStart Debug.Assert(_lineBufferOffset >= start AndAlso _lineBufferOffset >= 0) ResetTokens() Return TextSpan.FromBounds(start, condLineStart) End Function Private Sub EatThroughLine() While CanGet() Dim c As Char = Peek() If IsNewLine(c) Then EatThroughLineBreak(c) Return Else AdvanceChar() End If End While End Sub ''' <summary> ''' Gets a chunk of text as a DisabledCode node. ''' </summary> ''' <param name="span">The range of text.</param> ''' <returns>The DisabledCode node.</returns> Friend Function GetDisabledTextAt(span As TextSpan) As SyntaxTrivia If span.Start >= 0 AndAlso span.End <= _bufferLen Then Return SyntaxFactory.DisabledTextTrivia(GetTextNotInterned(span.Start, span.Length)) End If ' TODO: should this be a Require? Throw New ArgumentOutOfRangeException(NameOf(span)) End Function #End Region #Region "Interning" Friend Function GetScratchTextInterned(sb As StringBuilder) As String Dim str = _stringTable.Add(sb) sb.Clear() Return str End Function Friend Shared Function GetScratchText(sb As StringBuilder) As String ' PERF: Special case for the very common case of a string containing a single space Dim str As String If sb.Length = 1 AndAlso sb(0) = " "c Then str = " " Else str = sb.ToString End If sb.Clear() Return str End Function ' This overload of GetScratchText first examines the contents of the StringBuilder to ' see if it matches the given string. If so, then the given string is returned, saving ' the allocation. Private Shared Function GetScratchText(sb As StringBuilder, text As String) As String Dim str As String If StringTable.TextEquals(text, sb) Then str = text Else str = sb.ToString End If sb.Clear() Return str End Function Friend Function Intern(s As String, start As Integer, length As Integer) As String Return _stringTable.Add(s, start, length) End Function Friend Function Intern(s As Char(), start As Integer, length As Integer) As String Return _stringTable.Add(s, start, length) End Function Friend Function Intern(ch As Char) As String Return _stringTable.Add(ch) End Function Friend Function Intern(arr As Char()) As String Return _stringTable.Add(arr) End Function #End Region #Region "Buffer helpers" Private Function NextAre(chars As String) As Boolean Return NextAre(0, chars) End Function Private Function NextAre(offset As Integer, chars As String) As Boolean Debug.Assert(Not String.IsNullOrEmpty(chars)) Dim n = chars.Length If Not CanGet(offset + n - 1) Then Return False For i = 0 To n - 1 If chars(i) <> Peek(offset + i) Then Return False Next Return True End Function Private Function NextIs(offset As Integer, c As Char) As Boolean Return CanGet(offset) AndAlso (Peek(offset) = c) End Function Private Function CanGet() As Boolean Return _lineBufferOffset < _bufferLen End Function Private Function CanGet(num As Integer) As Boolean Debug.Assert(_lineBufferOffset + num >= 0) Debug.Assert(num >= -MaxCharsLookBehind) Return _lineBufferOffset + num < _bufferLen End Function Private Function RemainingLength() As Integer Dim result = _bufferLen - _lineBufferOffset Debug.Assert(CanGet(result - 1)) Return result End Function Private Function GetText(length As Integer) As String Debug.Assert(length > 0) Debug.Assert(CanGet(length - 1)) If length = 1 Then Return GetNextChar() End If Dim str = GetText(_lineBufferOffset, length) AdvanceChar(length) Return str End Function Private Function GetTextNotInterned(length As Integer) As String Debug.Assert(length > 0) Debug.Assert(CanGet(length - 1)) If length = 1 Then ' we will still intern single chars. There could not be too many. Return GetNextChar() End If Dim str = GetTextNotInterned(_lineBufferOffset, length) AdvanceChar(length) Return str End Function Private Sub AdvanceChar(Optional howFar As Integer = 1) Debug.Assert(howFar > 0) Debug.Assert(CanGet(howFar - 1)) _lineBufferOffset += howFar End Sub Private Function GetNextChar() As String Debug.Assert(CanGet) Dim ch = GetChar() _lineBufferOffset += 1 Return ch End Function Private Sub EatThroughLineBreak(StartCharacter As Char) AdvanceChar(LengthOfLineBreak(StartCharacter)) End Sub Private Function SkipLineBreak(StartCharacter As Char, index As Integer) As Integer Return index + LengthOfLineBreak(StartCharacter, index) End Function Private Function LengthOfLineBreak(StartCharacter As Char, Optional here As Integer = 0) As Integer Debug.Assert(CanGet(here)) Debug.Assert(IsNewLine(StartCharacter)) Debug.Assert(StartCharacter = Peek(here)) If StartCharacter = CARRIAGE_RETURN AndAlso NextIs(here + 1, LINE_FEED) Then Return 2 End If Return 1 End Function #End Region #Region "New line and explicit line continuation." ''' <summary> ''' Accept a CR/LF pair or either in isolation as a newline. ''' Make it a statement separator ''' </summary> Private Function ScanNewlineAsStatementTerminator(startCharacter As Char, precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken If _lineBufferOffset < _endOfTerminatorTrivia Then Dim width = LengthOfLineBreak(startCharacter) Return MakeStatementTerminatorToken(precedingTrivia, width) Else Return MakeEmptyToken(precedingTrivia) End If End Function Private Function ScanColonAsStatementTerminator(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As SyntaxToken If _lineBufferOffset < _endOfTerminatorTrivia Then Return MakeColonToken(precedingTrivia, charIsFullWidth) Else Return MakeEmptyToken(precedingTrivia) End If End Function ''' <summary> ''' Accept a CR/LF pair or either in isolation as a newline. ''' Make it a whitespace ''' </summary> Private Function ScanNewlineAsTrivia(StartCharacter As Char) As SyntaxTrivia If LengthOfLineBreak(StartCharacter) = 2 Then Return MakeEndOfLineTriviaCRLF() End If Return MakeEndOfLineTrivia(GetNextChar) End Function Private Function TryGet(num As Integer, ByRef ch As Char) As Boolean If CanGet(num) Then ch = Peek(num) Return True End If Return False End Function Private Function ScanLineContinuation(tList As SyntaxListBuilder) As Boolean Dim ch As Char = ChrW(0) If Not TryGet(0, ch) Then Return False End If If Not IsAfterWhitespace() Then Return False End If If Not IsUnderscore(ch) Then Return False End If Dim here = GetWhitespaceLength(1) TryGet(here, ch) Dim foundComment = IsSingleQuote(ch) Dim atNewLine As Boolean = IsNewLine(ch) If Not foundComment AndAlso Not atNewLine AndAlso CanGet(here) Then Return False End If tList.Add(MakeLineContinuationTrivia(GetText(1))) If here > 1 Then tList.Add(MakeWhiteSpaceTrivia(GetText(here - 1))) End If If foundComment Then Dim comment As SyntaxTrivia = ScanComment() If Not CheckFeatureAvailability(Feature.CommentsAfterLineContinuation) Then comment = comment.WithDiagnostics({ErrorFactory.ErrorInfo(ERRID.ERR_CommentsAfterLineContinuationNotAvailable1, New VisualBasicRequiredLanguageVersion(Feature.CommentsAfterLineContinuation.GetLanguageVersion()))}) End If tList.Add(comment) ' Need to call CanGet here to prevent Peek reading past EndOfBuffer. This can happen when file ends with comment but no New Line. If CanGet() Then ch = Peek() atNewLine = IsNewLine(ch) Else Debug.Assert(Not atNewLine) End If End If If atNewLine Then Dim newLine = SkipLineBreak(ch, 0) here = GetWhitespaceLength(newLine) Dim spaces = here - newLine Dim startComment = PeekStartComment(here) ' If the line following the line continuation is blank, or blank with a comment, ' do not include the new line character since that would confuse code handling ' implicit line continuations. (See Scanner::EatLineContinuation.) Otherwise, ' include the new line and any additional spaces as trivia. If startComment = 0 AndAlso CanGet(here) AndAlso Not IsNewLine(Peek(here)) Then tList.Add(MakeEndOfLineTrivia(GetText(newLine))) If spaces > 0 Then tList.Add(MakeWhiteSpaceTrivia(GetText(spaces))) End If End If End If Return True End Function #End Region #Region "Trivia" ''' <summary> ''' Consumes all trivia until a nontrivia char is found ''' </summary> Friend Function ScanMultilineTrivia() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) If Not CanGet() Then Return Nothing End If Dim ch = Peek() ' optimization for a common case ' the ASCII range between ': and ~ , with exception of except "'", "_" and R cannot start trivia If ch > ":"c AndAlso ch <= "~"c AndAlso ch <> "'"c AndAlso ch <> "_"c AndAlso ch <> "R"c AndAlso ch <> "r"c AndAlso ch <> "<"c AndAlso ch <> "="c AndAlso ch <> ">"c Then Return Nothing End If Dim triviaList = _triviaListPool.Allocate() While TryScanSinglePieceOfMultilineTrivia(triviaList) End While Dim result = MakeTriviaArray(triviaList) _triviaListPool.Free(triviaList) Return result End Function ''' <summary> ''' Scans a single piece of trivia ''' </summary> Private Function TryScanSinglePieceOfMultilineTrivia(tList As SyntaxListBuilder) As Boolean If CanGet() Then Dim atNewLine = IsAtNewLine() ' check for XmlDocComment and directives If atNewLine Then If StartsXmlDoc(0) Then Return TryScanXmlDocComment(tList) End If If StartsDirective(0) Then Return TryScanDirective(tList) End If If IsConflictMarkerTrivia() Then ScanConflictMarker(tList) Return True End If End If Dim ch = Peek() If IsWhitespace(ch) Then ' eat until linebreak or non-whitespace Dim wslen = GetWhitespaceLength(1) If atNewLine Then If StartsXmlDoc(wslen) Then Return TryScanXmlDocComment(tList) End If If StartsDirective(wslen) Then Return TryScanDirective(tList) End If End If tList.Add(MakeWhiteSpaceTrivia(GetText(wslen))) Return True ElseIf IsNewLine(ch) Then tList.Add(ScanNewlineAsTrivia(ch)) Return True ElseIf IsUnderscore(ch) Then Return ScanLineContinuation(tList) ElseIf IsColonAndNotColonEquals(ch, offset:=0) Then tList.Add(ScanColonAsTrivia()) Return True End If ' try get a comment Return ScanCommentIfAny(tList) End If Return False End Function ' All conflict markers consist of the same character repeated seven times. If it Is ' a <<<<<<< Or >>>>>>> marker then it Is also followed by a space. Private Shared ReadOnly s_conflictMarkerLength As Integer = "<<<<<<<".Length Private Function IsConflictMarkerTrivia() As Boolean If CanGet() Then Dim ch = Peek() If ch = "<"c OrElse ch = ">"c OrElse ch = "="c Then Dim position = _lineBufferOffset Dim text = _buffer If position = 0 OrElse SyntaxFacts.IsNewLine(text(position - 1)) Then Dim firstCh = _buffer(position) If (position + s_conflictMarkerLength) <= text.Length Then For i = 0 To s_conflictMarkerLength - 1 If text(position + i) <> firstCh Then Return False End If Next If firstCh = "="c Then Return True End If Return (position + s_conflictMarkerLength) < text.Length AndAlso text(position + s_conflictMarkerLength) = " "c End If End If End If End If Return False End Function Private Sub ScanConflictMarker(tList As SyntaxListBuilder) Dim startCh = Peek() ' First create a trivia from the start of this merge conflict marker to the ' end of line/file (whichever comes first). ScanConflictMarkerHeader(tList) ' Now add the newlines as the next trivia. ScanConflictMarkerEndOfLine(tList) If startCh = "="c Then ' Consume everything from the start of the mid-conflict marker to the start of the next ' end-conflict marker. ScanConflictMarkerDisabledText(tList) End If End Sub Private Sub ScanConflictMarkerDisabledText(tList As SyntaxListBuilder) Dim start = _lineBufferOffset While CanGet() Dim ch = Peek() If ch = ">"c AndAlso IsConflictMarkerTrivia() Then Exit While End If AdvanceChar() End While Dim width = _lineBufferOffset - start If width > 0 Then tList.Add(SyntaxFactory.DisabledTextTrivia(GetText(start, width))) End If End Sub Private Sub ScanConflictMarkerEndOfLine(tList As SyntaxListBuilder) Dim start = _lineBufferOffset While CanGet() AndAlso SyntaxFacts.IsNewLine(Peek()) AdvanceChar() End While Dim width = _lineBufferOffset - start If width > 0 Then tList.Add(SyntaxFactory.EndOfLineTrivia(GetText(start, width))) End If End Sub Private Sub ScanConflictMarkerHeader(tList As SyntaxListBuilder) Dim start = _lineBufferOffset While CanGet() Dim ch = Peek() If SyntaxFacts.IsNewLine(ch) Then Exit While End If AdvanceChar() End While Dim trivia = SyntaxFactory.ConflictMarkerTrivia(GetText(start, _lineBufferOffset - start)) trivia = DirectCast(trivia.SetDiagnostics({ErrorFactory.ErrorInfo(ERRID.ERR_Merge_conflict_marker_encountered)}), SyntaxTrivia) tList.Add(trivia) End Sub ' check for '''(~') Private Function StartsXmlDoc(here As Integer) As Boolean Return _options.DocumentationMode >= DocumentationMode.Parse AndAlso CanGet(here + 3) AndAlso IsSingleQuote(Peek(here)) AndAlso IsSingleQuote(Peek(here + 1)) AndAlso IsSingleQuote(Peek(here + 2)) AndAlso Not IsSingleQuote(Peek(here + 3)) End Function ' check for # Private Function StartsDirective(here As Integer) As Boolean If CanGet(here) Then Dim ch = Peek(here) Return IsHash(ch) End If Return False End Function Private Function IsAtNewLine() As Boolean Return _lineBufferOffset = 0 OrElse IsNewLine(Peek(-1)) End Function Private Function IsAfterWhitespace() As Boolean If _lineBufferOffset = 0 Then Return True End If Dim prevChar = Peek(-1) Return IsWhitespace(prevChar) End Function ''' <summary> ''' Scan trivia on one LOGICAL line ''' Will check for whitespace, comment, EoL, implicit line break ''' EoL may be consumed as whitespace only as a part of line continuation ( _ ) ''' </summary> Friend Function ScanSingleLineTrivia() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Dim tList = _triviaListPool.Allocate() ScanSingleLineTrivia(tList) Dim result = MakeTriviaArray(tList) _triviaListPool.Free(tList) Return result End Function Private Sub ScanSingleLineTrivia(tList As SyntaxListBuilder) If IsScanningXmlDoc Then ScanSingleLineTriviaInXmlDoc(tList) Else ScanWhitespaceAndLineContinuations(tList) ScanCommentIfAny(tList) ScanTerminatorTrivia(tList) End If End Sub Private Sub ScanSingleLineTriviaInXmlDoc(tList As SyntaxListBuilder) If CanGet() Then Dim c As Char = Peek() Select Case (c) ' // Whitespace ' // S ::= (#x20 | #x9 | #xD | #xA)+ Case CARRIAGE_RETURN, LINE_FEED, " "c, CHARACTER_TABULATION Dim offsets = CreateOffsetRestorePoint() Dim triviaList = _triviaListPool.Allocate(Of VisualBasicSyntaxNode)() Dim continueLine = ScanXmlTriviaInXmlDoc(c, triviaList) If Not continueLine Then _triviaListPool.Free(triviaList) offsets.Restore() Return End If For i = 0 To triviaList.Count - 1 tList.Add(triviaList(i)) Next _triviaListPool.Free(triviaList) End Select End If End Sub Private Function ScanLeadingTrivia() As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Dim tList = _triviaListPool.Allocate() ScanWhitespaceAndLineContinuations(tList) Dim result = MakeTriviaArray(tList) _triviaListPool.Free(tList) Return result End Function Private Sub ScanWhitespaceAndLineContinuations(tList As SyntaxListBuilder) If CanGet() AndAlso IsWhitespace(Peek()) Then tList.Add(ScanWhitespace(1)) ' collect { lineCont, ws } While ScanLineContinuation(tList) End While End If End Sub Private Function ScanSingleLineTrivia(includeFollowingBlankLines As Boolean) As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) Dim tList = _triviaListPool.Allocate() ScanSingleLineTrivia(tList) If includeFollowingBlankLines AndAlso IsBlankLine(tList) Then Dim more = _triviaListPool.Allocate() While True Dim offsets = CreateOffsetRestorePoint() _lineBufferOffset = _endOfTerminatorTrivia ScanSingleLineTrivia(more) If Not IsBlankLine(more) Then offsets.Restore() Exit While End If Dim n = more.Count For i = 0 To n - 1 tList.Add(more(i)) Next more.Clear() End While _triviaListPool.Free(more) End If Dim result = tList.ToList() _triviaListPool.Free(tList) Return result End Function ''' <summary> ''' Return True if the builder is a (possibly empty) list of ''' WhitespaceTrivia followed by an EndOfLineTrivia. ''' </summary> Private Shared Function IsBlankLine(tList As SyntaxListBuilder) As Boolean Dim n = tList.Count If n = 0 OrElse tList(n - 1).RawKind <> SyntaxKind.EndOfLineTrivia Then Return False End If For i = 0 To n - 2 If tList(i).RawKind <> SyntaxKind.WhitespaceTrivia Then Return False End If Next Return True End Function Private Sub ScanTerminatorTrivia(tList As SyntaxListBuilder) ' Check for statement terminators ' There are 4 special cases ' 1. [colon ws+]* colon -> colon terminator ' 2. new line -> new line terminator ' 3. colon followed by new line -> colon terminator + new line terminator ' 4. new line followed by new line -> new line terminator + new line terminator ' Case 3 is required to parse single line if's and numeric labels. ' Case 4 is required to limit explicit line continuations to single new line If CanGet() Then Dim ch As Char = Peek() Dim startOfTerminatorTrivia = _lineBufferOffset If IsNewLine(ch) Then tList.Add(ScanNewlineAsTrivia(ch)) ElseIf IsColonAndNotColonEquals(ch, offset:=0) Then tList.Add(ScanColonAsTrivia()) ' collect { ws, colon } Do Dim len = GetWhitespaceLength(0) If Not CanGet(len) Then Exit Do End If ch = Peek(len) If Not IsColonAndNotColonEquals(ch, offset:=len) Then Exit Do End If If len > 0 Then tList.Add(MakeWhiteSpaceTrivia(GetText(len))) End If startOfTerminatorTrivia = _lineBufferOffset tList.Add(ScanColonAsTrivia()) Loop End If _endOfTerminatorTrivia = _lineBufferOffset ' Reset _lineBufferOffset to the start of the terminator trivia. ' When the scanner is asked for the next token, it will return a 0 length terminator or colon token. _lineBufferOffset = startOfTerminatorTrivia End If End Sub Private Function ScanCommentIfAny(tList As SyntaxListBuilder) As Boolean If CanGet() Then ' check for comment Dim comment = ScanComment() If comment IsNot Nothing Then tList.Add(comment) Return True End If End If Return False End Function Private Function GetWhitespaceLength(len As Integer) As Integer ' eat until linebreak or non-whitespace While CanGet(len) AndAlso IsWhitespace(Peek(len)) len += 1 End While Return len End Function Private Function GetXmlWhitespaceLength(len As Integer) As Integer ' eat until linebreak or non-whitespace While CanGet(len) AndAlso IsXmlWhitespace(Peek(len)) len += 1 End While Return len End Function Private Function ScanWhitespace(Optional len As Integer = 0) As VisualBasicSyntaxNode len = GetWhitespaceLength(len) If len > 0 Then Return MakeWhiteSpaceTrivia(GetText(len)) End If Return Nothing End Function Private Function ScanXmlWhitespace(Optional len As Integer = 0) As VisualBasicSyntaxNode len = GetXmlWhitespaceLength(len) If len > 0 Then Return MakeWhiteSpaceTrivia(GetText(len)) End If Return Nothing End Function Private Sub EatWhitespace() Debug.Assert(CanGet) Debug.Assert(IsWhitespace(Peek())) AdvanceChar() ' eat until linebreak or non-whitespace While CanGet() AndAlso IsWhitespace(Peek) AdvanceChar() End While End Sub Private Function PeekStartComment(i As Integer) As Integer If CanGet(i) Then Dim ch = Peek(i) If IsSingleQuote(ch) Then Return 1 ElseIf MatchOneOrAnotherOrFullwidth(ch, "R"c, "r"c) AndAlso CanGet(i + 2) AndAlso MatchOneOrAnotherOrFullwidth(Peek(i + 1), "E"c, "e"c) AndAlso MatchOneOrAnotherOrFullwidth(Peek(i + 2), "M"c, "m"c) Then If Not CanGet(i + 3) OrElse IsNewLine(Peek(i + 3)) Then ' have only 'REM' Return 3 ElseIf Not IsIdentifierPartCharacter(Peek(i + 3)) Then ' have 'REM ' Return 4 End If End If End If Return 0 End Function Private Function ScanComment() As SyntaxTrivia Debug.Assert(CanGet()) Dim length = PeekStartComment(0) If length > 0 Then Dim looksLikeDocComment As Boolean = StartsXmlDoc(0) ' eat all chars until EoL While CanGet(length) AndAlso Not IsNewLine(Peek(length)) length += 1 End While Dim commentTrivia As SyntaxTrivia = MakeCommentTrivia(GetTextNotInterned(length)) If looksLikeDocComment AndAlso _options.DocumentationMode >= DocumentationMode.Diagnose Then commentTrivia = commentTrivia.WithDiagnostics(ErrorFactory.ErrorInfo(ERRID.WRN_XMLDocNotFirstOnLine)) End If Return commentTrivia End If Return Nothing End Function ''' <summary> ''' Return True if the character is a colon, and not part of ":=". ''' </summary> Private Function IsColonAndNotColonEquals(ch As Char, offset As Integer) As Boolean Return IsColon(ch) AndAlso Not TrySkipFollowingEquals(offset + 1) End Function Private Function ScanColonAsTrivia() As SyntaxTrivia Debug.Assert(CanGet()) Debug.Assert(IsColonAndNotColonEquals(Peek(), offset:=0)) Return MakeColonTrivia(GetText(1)) End Function #End Region Private Function ScanTokenCommon(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), ch As Char, fullWidth As Boolean) As SyntaxToken Dim lengthWithMaybeEquals As Integer = 1 Select Case ch Case CARRIAGE_RETURN, LINE_FEED Return ScanNewlineAsStatementTerminator(ch, precedingTrivia) Case NEXT_LINE, LINE_SEPARATOR, PARAGRAPH_SEPARATOR If Not fullWidth Then Return ScanNewlineAsStatementTerminator(ch, precedingTrivia) End If Case " "c, CHARACTER_TABULATION, "'"c Debug.Assert(False, $"Unexpected char: &H{AscW(ch):x}") Return Nothing ' trivia cannot start a token Case "@"c Return MakeAtToken(precedingTrivia, fullWidth) Case "("c Return MakeOpenParenToken(precedingTrivia, fullWidth) Case ")"c Return MakeCloseParenToken(precedingTrivia, fullWidth) Case "{"c Return MakeOpenBraceToken(precedingTrivia, fullWidth) Case "}"c Return MakeCloseBraceToken(precedingTrivia, fullWidth) Case ","c Return MakeCommaToken(precedingTrivia, fullWidth) Case "#"c Dim dl = ScanDateLiteral(precedingTrivia) Return If(dl, MakeHashToken(precedingTrivia, fullWidth)) Case "&"c If CanGet(1) AndAlso BeginsBaseLiteral(Peek(1)) Then Return ScanNumericLiteral(precedingTrivia) End If If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeAmpersandEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeAmpersandToken(precedingTrivia, fullWidth) End If Case "="c Return MakeEqualsToken(precedingTrivia, fullWidth) Case "<"c Return ScanLeftAngleBracket(precedingTrivia, fullWidth, _scanSingleLineTriviaFunc) Case ">"c Return ScanRightAngleBracket(precedingTrivia, fullWidth) Case ":"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeColonEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return ScanColonAsStatementTerminator(precedingTrivia, fullWidth) End If Case "+"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakePlusEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakePlusToken(precedingTrivia, fullWidth) End If Case "-"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeMinusEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeMinusToken(precedingTrivia, fullWidth) End If Case "*"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeAsteriskEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeAsteriskToken(precedingTrivia, fullWidth) End If Case "/"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeSlashEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeSlashToken(precedingTrivia, fullWidth) End If Case "\"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeBackSlashEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeBackslashToken(precedingTrivia, fullWidth) End If Case "^"c If TrySkipFollowingEquals(lengthWithMaybeEquals) Then Return MakeCaretEqualsToken(precedingTrivia, lengthWithMaybeEquals) Else Return MakeCaretToken(precedingTrivia, fullWidth) End If Case "!"c Return MakeExclamationToken(precedingTrivia, fullWidth) Case "."c If CanGet(1) AndAlso IsDecimalDigit(Peek(1)) Then Return ScanNumericLiteral(precedingTrivia) Else Return MakeDotToken(precedingTrivia, fullWidth) End If Case "0"c, "1"c, "2"c, "3"c, "4"c, "5"c, "6"c, "7"c, "8"c, "9"c Return ScanNumericLiteral(precedingTrivia) Case """"c Return ScanStringLiteral(precedingTrivia) Case "A"c If NextAre(1, "s ") Then ' TODO: do we allow widechars in keywords? AdvanceChar(2) Return MakeKeyword(SyntaxKind.AsKeyword, "As", precedingTrivia) Else Return ScanIdentifierOrKeyword(precedingTrivia) End If Case "E"c If NextAre(1, "nd ") Then ' TODO: do we allow widechars in keywords? AdvanceChar(3) Return MakeKeyword(SyntaxKind.EndKeyword, "End", precedingTrivia) Else Return ScanIdentifierOrKeyword(precedingTrivia) End If Case "I"c If NextAre(1, "f ") Then ' TODO: do we allow widechars in keywords? AdvanceChar(2) Return MakeKeyword(SyntaxKind.IfKeyword, "If", precedingTrivia) Else Return ScanIdentifierOrKeyword(precedingTrivia) End If Case "a"c, "b"c, "c"c, "d"c, "e"c, "f"c, "g"c, "h"c, "i"c, "j"c, "k"c, "l"c, "m"c, "n"c, "o"c, "p"c, "q"c, "r"c, "s"c, "t"c, "u"c, "v"c, "w"c, "x"c, "y"c, "z"c Return ScanIdentifierOrKeyword(precedingTrivia) Case "B"c, "C"c, "D"c, "F"c, "G"c, "H"c, "J"c, "K"c, "L"c, "M"c, "N"c, "O"c, "P"c, "Q"c, "R"c, "S"c, "T"c, "U"c, "V"c, "W"c, "X"c, "Y"c, "Z"c Return ScanIdentifierOrKeyword(precedingTrivia) Case "_"c If CanGet(1) AndAlso IsIdentifierPartCharacter(Peek(1)) Then Return ScanIdentifierOrKeyword(precedingTrivia) End If Dim err As ERRID = ERRID.ERR_ExpectedIdentifier Dim len = GetWhitespaceLength(1) If Not CanGet(len) OrElse IsNewLine(Peek(len)) OrElse PeekStartComment(len) > 0 Then err = ERRID.ERR_LineContWithCommentOrNoPrecSpace End If ' not a line continuation and cannot start identifier. Return MakeBadToken(precedingTrivia, 1, err) Case "["c Return ScanBracketedIdentifier(precedingTrivia) Case "?"c Return MakeQuestionToken(precedingTrivia, fullWidth) Case "%"c If NextIs(1, ">"c) Then Return XmlMakeEndEmbeddedToken(precedingTrivia, _scanSingleLineTriviaFunc) End If Case "$"c, FULLWIDTH_DOLLAR_SIGN If Not fullWidth AndAlso CanGet(1) AndAlso IsDoubleQuote(Peek(1)) Then Return MakePunctuationToken(precedingTrivia, 2, SyntaxKind.DollarSignDoubleQuoteToken) End If End Select If IsIdentifierStartCharacter(ch) Then Return ScanIdentifierOrKeyword(precedingTrivia) End If Debug.Assert(Not IsNewLine(ch)) If fullWidth Then Debug.Assert(Not IsDoubleQuote(ch)) Return Nothing End If If IsDoubleQuote(ch) Then Return ScanStringLiteral(precedingTrivia) End If If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) Return ScanTokenFullWidth(precedingTrivia, ch) End If Return Nothing End Function ' at this point it is very likely that we are located at the beginning of a token Private Function TryScanToken(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken If CanGet() Then Return ScanTokenCommon(precedingTrivia, Peek(), False) End If Return MakeEofToken(precedingTrivia) End Function Private Function ScanTokenFullWidth(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), ch As Char) As SyntaxToken Return ScanTokenCommon(precedingTrivia, ch, True) End Function ' // Allow whitespace between the characters of a two-character token. Private Function TrySkipFollowingEquals(ByRef index As Integer) As Boolean Debug.Assert(index > 0) Debug.Assert(CanGet(index - 1)) Dim here = index Dim eq As Char While CanGet(here) eq = Peek(here) here += 1 If Not IsWhitespace(eq) Then If eq = "="c OrElse eq = FULLWIDTH_EQUALS_SIGN Then index = here Return True Else Return False End If End If End While Return False End Function Private Function ScanRightAngleBracket(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean) As SyntaxToken Debug.Assert(CanGet) ' > Debug.Assert(Peek() = ">"c OrElse Peek() = FULLWIDTH_GREATER_THAN_SIGN) Dim length As Integer = 1 ' // Allow whitespace between the characters of a two-character token. length = GetWhitespaceLength(length) If CanGet(length) Then Dim c As Char = Peek(length) If c = "="c OrElse c = FULLWIDTH_EQUALS_SIGN Then length += 1 Return MakeGreaterThanEqualsToken(precedingTrivia, length) ElseIf c = ">"c OrElse c = FULLWIDTH_GREATER_THAN_SIGN Then length += 1 If TrySkipFollowingEquals(length) Then Return MakeGreaterThanGreaterThanEqualsToken(precedingTrivia, length) Else Return MakeGreaterThanGreaterThanToken(precedingTrivia, length) End If End If End If Return MakeGreaterThanToken(precedingTrivia, charIsFullWidth) End Function Private Function ScanLeftAngleBracket(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode), charIsFullWidth As Boolean, scanTrailingTrivia As ScanTriviaFunc) As SyntaxToken Debug.Assert(CanGet) ' < Debug.Assert(Peek() = "<"c OrElse Peek() = FULLWIDTH_LESS_THAN_SIGN) Dim length As Integer = 1 ' Check for XML tokens If Not charIsFullWidth AndAlso CanGet(length) Then Dim c As Char = Peek(length) Select Case c Case "!"c If CanGet(length + 2) Then Select Case (Peek(length + 1)) Case "-"c If CanGet(length + 3) AndAlso Peek(length + 2) = "-"c Then Return XmlMakeBeginCommentToken(precedingTrivia, scanTrailingTrivia) End If Case "["c If NextAre(length + 2, "CDATA[") Then Return XmlMakeBeginCDataToken(precedingTrivia, scanTrailingTrivia) End If End Select End If Case "?"c Return XmlMakeBeginProcessingInstructionToken(precedingTrivia, scanTrailingTrivia) Case "/"c Return XmlMakeBeginEndElementToken(precedingTrivia, _scanSingleLineTriviaFunc) End Select End If ' // Allow whitespace between the characters of a two-character token. length = GetWhitespaceLength(length) If CanGet(length) Then Dim c As Char = Peek(length) If c = "="c OrElse c = FULLWIDTH_EQUALS_SIGN Then length += 1 Return MakeLessThanEqualsToken(precedingTrivia, length) ElseIf c = ">"c OrElse c = FULLWIDTH_GREATER_THAN_SIGN Then length += 1 Return MakeLessThanGreaterThanToken(precedingTrivia, length) ElseIf c = "<"c OrElse c = FULLWIDTH_LESS_THAN_SIGN Then length += 1 If CanGet(length) Then c = Peek(length) 'if the second "<" is a part of "<%" - like in "<<%" , we do not want to use it. If c <> "%"c AndAlso c <> FULLWIDTH_PERCENT_SIGN Then If TrySkipFollowingEquals(length) Then Return MakeLessThanLessThanEqualsToken(precedingTrivia, length) Else Return MakeLessThanLessThanToken(precedingTrivia, length) End If End If End If End If End If Return MakeLessThanToken(precedingTrivia, charIsFullWidth) End Function ''' <remarks> ''' Not intended for use in Expression Compiler scenarios. ''' </remarks> Friend Shared Function IsIdentifier(spelling As String) As Boolean Dim spellingLength As Integer = spelling.Length If spellingLength = 0 Then Return False End If Dim c = spelling(0) If SyntaxFacts.IsIdentifierStartCharacter(c) Then ' SPEC: ... Visual Basic identifiers conform to the Unicode Standard Annex 15 with one ' SPEC: exception: identifiers may begin with an underscore (connector) character. ' SPEC: If an identifier begins with an underscore, it must contain at least one other ' SPEC: valid identifier character to disambiguate it from a line continuation. If IsConnectorPunctuation(c) AndAlso spellingLength = 1 Then Return False End If For i = 1 To spellingLength - 1 If Not IsIdentifierPartCharacter(spelling(i)) Then Return False End If Next End If Return True End Function Private Function ScanIdentifierOrKeyword(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Debug.Assert(IsIdentifierStartCharacter(Peek)) Debug.Assert(PeekStartComment(0) = 0) ' comment should be handled by caller Dim ch = Peek() If CanGet(1) Then Dim ch1 = Peek(1) If IsConnectorPunctuation(ch) AndAlso Not IsIdentifierPartCharacter(ch1) Then Return MakeBadToken(precedingTrivia, 1, ERRID.ERR_ExpectedIdentifier) End If End If Dim len = 1 ' we know that the first char was good ' // The C++ compiler refuses to inline IsIdentifierCharacter, so the ' // < 128 test is inline here. (This loop gets a *lot* of traffic.) ' TODO: make sure we get good perf here While CanGet(len) ch = Peek(len) Dim code = Convert.ToUInt16(ch) If code < 128US AndAlso IsNarrowIdentifierCharacter(code) OrElse IsWideIdentifierCharacter(ch) Then len += 1 Else Exit While End If End While 'Check for a type character Dim TypeCharacter As TypeCharacter = TypeCharacter.None If CanGet(len) Then ch = Peek(len) FullWidthRepeat: Select Case ch Case "!"c ' // If the ! is followed by an identifier it is a dictionary lookup operator, not a type character. If CanGet(len + 1) Then Dim NextChar As Char = Peek(len + 1) If IsIdentifierStartCharacter(NextChar) OrElse MatchOneOrAnotherOrFullwidth(NextChar, "["c, "]"c) Then Exit Select End If End If TypeCharacter = TypeCharacter.Single 'typeChars.chType_sR4 len += 1 Case "#"c TypeCharacter = TypeCharacter.Double ' typeChars.chType_sR8 len += 1 Case "$"c TypeCharacter = TypeCharacter.String 'typeChars.chType_String len += 1 Case "%"c TypeCharacter = TypeCharacter.Integer ' typeChars.chType_sI4 len += 1 Case "&"c TypeCharacter = TypeCharacter.Long 'typeChars.chType_sI8 len += 1 Case "@"c TypeCharacter = TypeCharacter.Decimal 'chType_sDecimal len += 1 Case Else If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) GoTo FullWidthRepeat End If End Select End If Dim tokenType As SyntaxKind = SyntaxKind.IdentifierToken Dim contextualKind As SyntaxKind = SyntaxKind.IdentifierToken Dim spelling = GetText(len) Dim baseSpelling = If(TypeCharacter = TypeCharacter.None, spelling, Intern(spelling, 0, len - 1)) ' this can be keyword only if it has no type character, or if it is Mid$ If TypeCharacter = TypeCharacter.None Then tokenType = TokenOfStringCached(spelling) If SyntaxFacts.IsContextualKeyword(tokenType) Then contextualKind = tokenType tokenType = SyntaxKind.IdentifierToken End If ElseIf TokenOfStringCached(baseSpelling) = SyntaxKind.MidKeyword Then contextualKind = SyntaxKind.MidKeyword tokenType = SyntaxKind.IdentifierToken End If If tokenType <> SyntaxKind.IdentifierToken Then ' KEYWORD Return MakeKeyword(tokenType, spelling, precedingTrivia) Else ' IDENTIFIER or CONTEXTUAL Dim id As SyntaxToken = MakeIdentifier(spelling, contextualKind, False, baseSpelling, TypeCharacter, precedingTrivia) Return id End If End Function Private Function TokenOfStringCached(spelling As String) As SyntaxKind If spelling.Length > 16 Then Return SyntaxKind.IdentifierToken End If Return _KeywordsObjs.GetOrMakeValue(spelling) End Function Private Function ScanBracketedIdentifier(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) ' [ Debug.Assert(Peek() = "["c OrElse Peek() = FULLWIDTH_LEFT_SQUARE_BRACKET) Dim idStart As Integer = 1 Dim here As Integer = idStart Dim invalidIdentifier As Boolean = False If Not CanGet(here) Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_MissingEndBrack) End If Dim ch = Peek(here) ' check if we can start an ident. If Not IsIdentifierStartCharacter(ch) OrElse (IsConnectorPunctuation(ch) AndAlso Not (CanGet(here + 1) AndAlso IsIdentifierPartCharacter(Peek(here + 1)))) Then invalidIdentifier = True End If ' check ident until ] While CanGet(here) Dim [Next] As Char = Peek(here) If [Next] = "]"c OrElse [Next] = FULLWIDTH_RIGHT_SQUARE_BRACKET Then Dim idStringLength As Integer = here - idStart If idStringLength > 0 AndAlso Not invalidIdentifier Then Dim spelling = GetText(idStringLength + 2) ' TODO: this should be provable? Debug.Assert(spelling.Length > idStringLength + 1) ' TODO: consider interning. Dim baseText = spelling.Substring(1, idStringLength) Dim id As SyntaxToken = MakeIdentifier( spelling, SyntaxKind.IdentifierToken, True, baseText, TypeCharacter.None, precedingTrivia) Return id Else ' // The sequence "[]" does not define a valid identifier. Return MakeBadToken(precedingTrivia, here + 1, ERRID.ERR_ExpectedIdentifier) End If ElseIf IsNewLine([Next]) Then Exit While ElseIf Not IsIdentifierPartCharacter([Next]) Then invalidIdentifier = True Exit While End If here += 1 End While If here > 1 Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_MissingEndBrack) Else Return MakeBadToken(precedingTrivia, here, ERRID.ERR_ExpectedIdentifier) End If End Function Private Enum NumericLiteralKind Integral Float [Decimal] End Enum Private Function ScanNumericLiteral(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Dim here As Integer = 0 Dim integerLiteralStart As Integer Dim UnderscoreInWrongPlace As Boolean Dim UnderscoreUsed As Boolean = False Dim LeadingUnderscoreUsed = False Dim base As LiteralBase = LiteralBase.Decimal Dim literalKind As NumericLiteralKind = NumericLiteralKind.Integral ' #################################################### ' // Validate literal and find where the number starts and ends. ' #################################################### ' // First read a leading base specifier, if present, followed by a sequence of zero ' // or more digits. Dim ch = Peek() If ch = "&"c OrElse ch = FULLWIDTH_AMPERSAND Then here += 1 ch = If(CanGet(here), Peek(here), ChrW(0)) FullWidthRepeat: Select Case ch Case "H"c, "h"c here += 1 integerLiteralStart = here base = LiteralBase.Hexadecimal If CanGet(here) AndAlso Peek(here) = "_"c Then LeadingUnderscoreUsed = True End If While CanGet(here) ch = Peek(here) If Not IsHexDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Case "B"c, "b"c here += 1 integerLiteralStart = here base = LiteralBase.Binary If CanGet(here) AndAlso Peek(here) = "_"c Then LeadingUnderscoreUsed = True End If While CanGet(here) ch = Peek(here) If Not IsBinaryDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Case "O"c, "o"c here += 1 integerLiteralStart = here base = LiteralBase.Octal If CanGet(here) AndAlso Peek(here) = "_"c Then LeadingUnderscoreUsed = True End If While CanGet(here) ch = Peek(here) If Not IsOctalDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Case Else If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) GoTo FullWidthRepeat End If Throw ExceptionUtilities.UnexpectedValue(ch) End Select Else ' no base specifier - just go through decimal digits. integerLiteralStart = here UnderscoreInWrongPlace = (CanGet(here) AndAlso Peek(here) = "_"c) While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) AndAlso ch <> "_"c Then Exit While End If If ch = "_"c Then UnderscoreUsed = True End If here += 1 End While If here <> integerLiteralStart Then UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) End If End If ' we may have a dot, and then it is a float, but if this is an integral, then we have seen it all. Dim integerLiteralEnd As Integer = here ' // Unless there was an explicit base specifier (which indicates an integer literal), ' // read the rest of a float literal. If base = LiteralBase.Decimal AndAlso CanGet(here) Then ' // First read a '.' followed by a sequence of one or more digits. ch = Peek(here) If (ch = "."c Or ch = FULLWIDTH_FULL_STOP) AndAlso CanGet(here + 1) AndAlso IsDecimalDigit(Peek(here + 1)) Then here += 2 ' skip dot and first digit ' all following decimal digits belong to the literal (fractional part) While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) AndAlso ch <> "_"c Then Exit While End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) literalKind = NumericLiteralKind.Float End If ' // Read an exponent symbol followed by an optional sign and a sequence of ' // one or more digits. If CanGet(here) AndAlso BeginsExponent(Peek(here)) Then here += 1 If CanGet(here) Then ch = Peek(here) If MatchOneOrAnotherOrFullwidth(ch, "+"c, "-"c) Then here += 1 End If End If If CanGet(here) AndAlso IsDecimalDigit(Peek(here)) Then here += 1 While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) AndAlso ch <> "_"c Then Exit While End If here += 1 End While UnderscoreInWrongPlace = UnderscoreInWrongPlace Or (Peek(here - 1) = "_"c) Else Return MakeBadToken(precedingTrivia, here, ERRID.ERR_InvalidLiteralExponent) End If literalKind = NumericLiteralKind.Float End If End If Dim literalWithoutTypeChar = here ' #################################################### ' // Read a trailing type character. ' #################################################### Dim TypeCharacter As TypeCharacter = TypeCharacter.None If CanGet(here) Then ch = Peek(here) FullWidthRepeat2: Select Case ch Case "!"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.Single literalKind = NumericLiteralKind.Float here += 1 End If Case "F"c, "f"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.SingleLiteral literalKind = NumericLiteralKind.Float here += 1 End If Case "#"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.Double literalKind = NumericLiteralKind.Float here += 1 End If Case "R"c, "r"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.DoubleLiteral literalKind = NumericLiteralKind.Float here += 1 End If Case "S"c, "s"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.ShortLiteral here += 1 End If Case "%"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.Integer here += 1 End If Case "I"c, "i"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.IntegerLiteral here += 1 End If Case "&"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.Long here += 1 End If Case "L"c, "l"c If literalKind <> NumericLiteralKind.Float Then TypeCharacter = TypeCharacter.LongLiteral here += 1 End If Case "@"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.Decimal literalKind = NumericLiteralKind.Decimal here += 1 End If Case "D"c, "d"c If base = LiteralBase.Decimal Then TypeCharacter = TypeCharacter.DecimalLiteral literalKind = NumericLiteralKind.Decimal ' check if this was not attempt to use obsolete exponent If CanGet(here + 1) Then ch = Peek(here + 1) If IsDecimalDigit(ch) OrElse MatchOneOrAnotherOrFullwidth(ch, "+"c, "-"c) Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_ObsoleteExponent) End If End If here += 1 End If Case "U"c, "u"c If literalKind <> NumericLiteralKind.Float AndAlso CanGet(here + 1) Then Dim NextChar As Char = Peek(here + 1) 'unsigned suffixes - US, UL, UI If MatchOneOrAnotherOrFullwidth(NextChar, "S"c, "s"c) Then TypeCharacter = TypeCharacter.UShortLiteral here += 2 ElseIf MatchOneOrAnotherOrFullwidth(NextChar, "I"c, "i"c) Then TypeCharacter = TypeCharacter.UIntegerLiteral here += 2 ElseIf MatchOneOrAnotherOrFullwidth(NextChar, "L"c, "l"c) Then TypeCharacter = TypeCharacter.ULongLiteral here += 2 End If End If Case Else If IsFullWidth(ch) Then ch = MakeHalfWidth(ch) GoTo FullWidthRepeat2 End If End Select End If ' #################################################### ' // Produce a value for the literal. ' #################################################### Dim integralValue As UInt64 Dim floatingValue As Double Dim decimalValue As Decimal Dim Overflows As Boolean = False If literalKind = NumericLiteralKind.Integral Then If integerLiteralStart = integerLiteralEnd Then Return MakeBadToken(precedingTrivia, here, ERRID.ERR_Syntax) Else integralValue = 0 If base = LiteralBase.Decimal Then ' Init For loop For LiteralCharacter As Integer = integerLiteralStart To integerLiteralEnd - 1 Dim LiteralCharacterValue As Char = Peek(LiteralCharacter) If LiteralCharacterValue = "_"c Then Continue For End If Dim NextCharacterValue As UInteger = IntegralLiteralCharacterValue(LiteralCharacterValue) If integralValue < 1844674407370955161UL OrElse (integralValue = 1844674407370955161UL AndAlso NextCharacterValue <= 5UI) Then integralValue = (integralValue * 10UL) + NextCharacterValue Else Overflows = True Exit For End If Next If TypeCharacter <> TypeCharacter.ULongLiteral AndAlso integralValue > Long.MaxValue Then Overflows = True End If Else Dim Shift As Integer = If(base = LiteralBase.Hexadecimal, 4, If(Base = LiteralBase.Octal, 3, 1)) Dim OverflowMask As UInt64 = If(base = LiteralBase.Hexadecimal, &HF000000000000000UL, If(base = LiteralBase.Octal, &HE000000000000000UL, &H8000000000000000UL)) ' Init For loop For LiteralCharacter As Integer = integerLiteralStart To integerLiteralEnd - 1 Dim LiteralCharacterValue As Char = Peek(LiteralCharacter) If LiteralCharacterValue = "_"c Then Continue For End If If (integralValue And OverflowMask) <> 0 Then Overflows = True End If integralValue = (integralValue << Shift) + IntegralLiteralCharacterValue(LiteralCharacterValue) Next End If If TypeCharacter = TypeCharacter.None Then ' nothing to do ElseIf TypeCharacter = TypeCharacter.Integer OrElse TypeCharacter = TypeCharacter.IntegerLiteral Then If (base = LiteralBase.Decimal AndAlso integralValue > &H7FFFFFFF) OrElse integralValue > &HFFFFFFFFUI Then Overflows = True End If ElseIf TypeCharacter = TypeCharacter.UIntegerLiteral Then If integralValue > &HFFFFFFFFUI Then Overflows = True End If ElseIf TypeCharacter = TypeCharacter.ShortLiteral Then If (base = LiteralBase.Decimal AndAlso integralValue > &H7FFF) OrElse integralValue > &HFFFF Then Overflows = True End If ElseIf TypeCharacter = TypeCharacter.UShortLiteral Then If integralValue > &HFFFF Then Overflows = True End If Else Debug.Assert(TypeCharacter = TypeCharacter.Long OrElse TypeCharacter = TypeCharacter.LongLiteral OrElse TypeCharacter = TypeCharacter.ULongLiteral, "Integral literal value computation is lost.") End If End If Else ' // Copy the text of the literal to deal with fullwidth Dim scratch = GetScratch() For i = 0 To literalWithoutTypeChar - 1 Dim curCh = Peek(i) If curCh <> "_"c Then scratch.Append(If(IsFullWidth(curCh), MakeHalfWidth(curCh), curCh)) End If Next Dim LiteralSpelling = GetScratchTextInterned(scratch) If literalKind = NumericLiteralKind.Decimal Then ' Attempt to convert to Decimal. Overflows = Not GetDecimalValue(LiteralSpelling, decimalValue) Else If TypeCharacter = TypeCharacter.Single OrElse TypeCharacter = TypeCharacter.SingleLiteral Then ' // Attempt to convert to single Dim SingleValue As Single If Not RealParser.TryParseFloat(LiteralSpelling, SingleValue) Then Overflows = True Else floatingValue = SingleValue End If Else ' // Attempt to convert to double. If Not RealParser.TryParseDouble(LiteralSpelling, floatingValue) Then Overflows = True End If End If End If End If Dim result As SyntaxToken Select Case literalKind Case NumericLiteralKind.Integral result = MakeIntegerLiteralToken(precedingTrivia, base, TypeCharacter, If(Overflows Or UnderscoreInWrongPlace, 0UL, IntegralValue), here) Case NumericLiteralKind.Float result = MakeFloatingLiteralToken(precedingTrivia, TypeCharacter, If(Overflows Or UnderscoreInWrongPlace, 0.0F, floatingValue), here) Case NumericLiteralKind.Decimal result = MakeDecimalLiteralToken(precedingTrivia, TypeCharacter, If(Overflows Or UnderscoreInWrongPlace, 0D, decimalValue), here) Case Else Throw ExceptionUtilities.UnexpectedValue(literalKind) End Select If Overflows Then result = DirectCast(result.AddError(ErrorFactory.ErrorInfo(ERRID.ERR_Overflow)), SyntaxToken) End If If UnderscoreInWrongPlace Then result = DirectCast(result.AddError(ErrorFactory.ErrorInfo(ERRID.ERR_Syntax)), SyntaxToken) ElseIf LeadingUnderscoreUsed Then result = CheckFeatureAvailability(result, Feature.LeadingDigitSeparator) ElseIf UnderscoreUsed Then result = CheckFeatureAvailability(result, Feature.DigitSeparators) End If If base = LiteralBase.Binary Then result = CheckFeatureAvailability(result, Feature.BinaryLiterals) End If Return result End Function Private Shared Function GetDecimalValue(text As String, <Out()> ByRef value As Decimal) As Boolean ' Use Decimal.TryParse to parse value. Note: the behavior of ' Decimal.TryParse differs from Dev11 in the following cases: ' ' 1. [-]0eNd where N > 0 ' The native compiler ignores sign and scale and treats such cases ' as 0e0d. Decimal.TryParse fails so these cases are compile errors. ' [Bug #568475] ' 2. Decimals with significant digits below 1e-49 ' The native compiler considers digits below 1e-49 when rounding. ' Decimal.TryParse ignores digits below 1e-49 when rounding. This ' difference is perhaps the most significant since existing code will ' continue to compile but constant values may be rounded differently. ' [Bug #568494] Return Decimal.TryParse(text, NumberStyles.AllowDecimalPoint Or NumberStyles.AllowExponent, CultureInfo.InvariantCulture, value) End Function Private Function ScanIntLiteral( ByRef ReturnValue As Integer, ByRef here As Integer ) As Boolean Debug.Assert(here >= 0) If Not CanGet(here) Then Return False End If Dim ch = Peek(here) If Not IsDecimalDigit(ch) Then Return False End If Dim integralValue As Integer = IntegralLiteralCharacterValue(ch) here += 1 While CanGet(here) ch = Peek(here) If Not IsDecimalDigit(ch) Then Exit While End If Dim nextDigit = IntegralLiteralCharacterValue(ch) If integralValue < 214748364 OrElse (integralValue = 214748364 AndAlso nextDigit < 8) Then integralValue = integralValue * 10 + nextDigit here += 1 Else Return False End If End While ReturnValue = integralValue Return True End Function Private Function ScanDateLiteral(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Debug.Assert(IsHash(Peek())) Dim here As Integer = 1 'skip # Dim firstValue As Integer Dim YearValue, MonthValue, DayValue, HourValue, MinuteValue, SecondValue As Integer Dim haveDateValue As Boolean = False Dim haveYearValue As Boolean = False Dim haveTimeValue As Boolean = False Dim haveMinuteValue As Boolean = False Dim haveSecondValue As Boolean = False Dim haveAM As Boolean = False Dim havePM As Boolean = False Dim dateIsInvalid As Boolean = False Dim YearIsTwoDigits As Boolean = False Dim daysToMonth As Integer() = Nothing Dim yearIsFirst As Boolean = False ' // Unfortunately, we can't fall back on OLE Automation's date parsing because ' // they don't have the same range as the URT's DateTime class ' // First, eat any whitespace here = GetWhitespaceLength(here) Dim firstValueStart As Integer = here ' // The first thing has to be an integer, although it's not clear what it is yet If Not ScanIntLiteral(firstValue, here) Then Return Nothing End If ' // If we see a /, then it's a date If CanGet(here) AndAlso IsDateSeparatorCharacter(Peek(here)) Then Dim FirstDateSeparator As Integer = here ' // We've got a date haveDateValue = True here += 1 ' Is the first value a year? ' It is a year if it consists of exactly 4 digits. ' Condition below uses 5 because we already skipped the separator. If here - firstValueStart = 5 Then haveYearValue = True yearIsFirst = True YearValue = firstValue ' // We have to have a month value If Not ScanIntLiteral(MonthValue, here) Then GoTo baddate End If ' Do we have a day value? If CanGet(here) AndAlso IsDateSeparatorCharacter(Peek(here)) Then ' // Check to see they used a consistent separator If Peek(here) <> Peek(FirstDateSeparator) Then GoTo baddate End If ' // Yes. here += 1 If Not ScanIntLiteral(DayValue, here) Then GoTo baddate End If End If Else ' First value is month MonthValue = firstValue ' // We have to have a day value If Not ScanIntLiteral(DayValue, here) Then GoTo baddate End If ' // Do we have a year value? If CanGet(here) AndAlso IsDateSeparatorCharacter(Peek(here)) Then ' // Check to see they used a consistent separator If Peek(here) <> Peek(FirstDateSeparator) Then GoTo baddate End If ' // Yes. haveYearValue = True here += 1 Dim YearStart As Integer = here If Not ScanIntLiteral(YearValue, here) Then GoTo baddate End If If (here - YearStart) = 2 Then YearIsTwoDigits = True End If End If End If here = GetWhitespaceLength(here) End If ' // If we haven't seen a date, assume it's a time value If Not haveDateValue Then haveTimeValue = True HourValue = firstValue Else ' // We did see a date. See if we see a time value... If ScanIntLiteral(HourValue, here) Then ' // Yup. haveTimeValue = True End If End If If haveTimeValue Then ' // Do we see a :? If CanGet(here) AndAlso IsColon(Peek(here)) Then here += 1 ' // Now let's get the minute value If Not ScanIntLiteral(MinuteValue, here) Then GoTo baddate End If haveMinuteValue = True ' // Do we have a second value? If CanGet(here) AndAlso IsColon(Peek(here)) Then ' // Yes. haveSecondValue = True here += 1 If Not ScanIntLiteral(SecondValue, here) Then GoTo baddate End If End If End If here = GetWhitespaceLength(here) ' // Check AM/PM If CanGet(here) Then If Peek(here) = "A"c OrElse Peek(here) = FULLWIDTH_LATIN_CAPITAL_LETTER_A OrElse Peek(here) = "a"c OrElse Peek(here) = FULLWIDTH_LATIN_SMALL_LETTER_A Then haveAM = True here += 1 ElseIf Peek(here) = "P"c OrElse Peek(here) = FULLWIDTH_LATIN_CAPITAL_LETTER_P OrElse Peek(here) = "p"c OrElse Peek(here) = FULLWIDTH_LATIN_SMALL_LETTER_P Then havePM = True here += 1 End If If CanGet(here) AndAlso (haveAM OrElse havePM) Then If Peek(here) = "M"c OrElse Peek(here) = FULLWIDTH_LATIN_CAPITAL_LETTER_M OrElse Peek(here) = "m"c OrElse Peek(here) = FULLWIDTH_LATIN_SMALL_LETTER_M Then here = GetWhitespaceLength(here + 1) Else GoTo baddate End If End If End If ' // If there's no minute/second value and no AM/PM, it's invalid If Not haveMinuteValue AndAlso Not haveAM AndAlso Not havePM Then GoTo baddate End If End If If Not CanGet(here) OrElse Not IsHash(Peek(here)) Then GoTo baddate End If here += 1 ' // OK, now we've got all the values, let's see if we've got a valid date If haveDateValue Then If MonthValue < 1 OrElse MonthValue > 12 Then dateIsInvalid = True End If ' // We'll check Days in a moment... If Not haveYearValue Then dateIsInvalid = True YearValue = 1 End If ' // Check if not a leap year If Not ((YearValue Mod 4 = 0) AndAlso (Not (YearValue Mod 100 = 0) OrElse (YearValue Mod 400 = 0))) Then daysToMonth = DaysToMonth365 Else daysToMonth = DaysToMonth366 End If If DayValue < 1 OrElse (Not dateIsInvalid AndAlso DayValue > daysToMonth(MonthValue) - daysToMonth(MonthValue - 1)) Then dateIsInvalid = True End If If YearIsTwoDigits Then dateIsInvalid = True End If If YearValue < 1 OrElse YearValue > 9999 Then dateIsInvalid = True End If Else MonthValue = 1 DayValue = 1 YearValue = 1 daysToMonth = DaysToMonth365 End If If haveTimeValue Then If haveAM OrElse havePM Then ' // 12-hour value If HourValue < 1 OrElse HourValue > 12 Then dateIsInvalid = True End If If haveAM Then HourValue = HourValue Mod 12 ElseIf havePM Then HourValue = HourValue + 12 If HourValue = 24 Then HourValue = 12 End If End If Else If HourValue < 0 OrElse HourValue > 23 Then dateIsInvalid = True End If End If If haveMinuteValue Then If MinuteValue < 0 OrElse MinuteValue > 59 Then dateIsInvalid = True End If Else MinuteValue = 0 End If If haveSecondValue Then If SecondValue < 0 OrElse SecondValue > 59 Then dateIsInvalid = True End If Else SecondValue = 0 End If Else HourValue = 0 MinuteValue = 0 SecondValue = 0 End If ' // Ok, we've got a valid value. Now make into an i8. If Not dateIsInvalid Then Dim DateTimeValue As New DateTime(YearValue, MonthValue, DayValue, HourValue, MinuteValue, SecondValue) Dim result = MakeDateLiteralToken(precedingTrivia, DateTimeValue, here) If yearIsFirst Then result = Parser.CheckFeatureAvailability(Feature.YearFirstDateLiterals, result, Options.LanguageVersion) End If Return result Else Return MakeBadToken(precedingTrivia, here, ERRID.ERR_InvalidDate) End If baddate: ' // If we can find a closing #, then assume it's a malformed date, ' // otherwise, it's not a date While CanGet(here) Dim ch As Char = Peek(here) If IsHash(ch) OrElse IsNewLine(ch) Then Exit While End If here += 1 End While If Not CanGet(here) OrElse IsNewLine(Peek(here)) Then ' // No closing # Return Nothing Else Debug.Assert(IsHash(Peek(here))) here += 1 ' consume trailing # Return MakeBadToken(precedingTrivia, here, ERRID.ERR_InvalidDate) End If End Function Private Function ScanStringLiteral(precedingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)) As SyntaxToken Debug.Assert(CanGet) Debug.Assert(IsDoubleQuote(Peek)) Dim length As Integer = 1 Dim ch As Char Dim followingTrivia As CoreInternalSyntax.SyntaxList(Of VisualBasicSyntaxNode) ' // Check for a Char literal, which can be of the form: ' // """"c or "<anycharacter-except-">"c If CanGet(3) AndAlso IsDoubleQuote(Peek(2)) Then If IsDoubleQuote(Peek(1)) Then If IsDoubleQuote(Peek(3)) AndAlso CanGet(4) AndAlso IsLetterC(Peek(4)) Then ' // Double-quote Char literal: """"c Return MakeCharacterLiteralToken(precedingTrivia, """"c, 5) End If ElseIf IsLetterC(Peek(3)) Then ' // Char literal. "x"c Return MakeCharacterLiteralToken(precedingTrivia, Peek(1), 4) End If End If If CanGet(2) AndAlso IsDoubleQuote(Peek(1)) AndAlso IsLetterC(Peek(2)) Then ' // Error. ""c is not a legal char constant Return MakeBadToken(precedingTrivia, 3, ERRID.ERR_IllegalCharConstant) End If Dim haveNewLine As Boolean = False Dim scratch = GetScratch() While CanGet(length) ch = Peek(length) If IsDoubleQuote(ch) Then If CanGet(length + 1) Then ch = Peek(length + 1) If IsDoubleQuote(ch) Then ' // An escaped double quote scratch.Append(""""c) length += 2 Continue While Else ' // The end of the char literal. If IsLetterC(ch) Then ' // Error. "aad"c is not a legal char constant ' // +2 to include both " and c in the token span scratch.Clear() Return MakeBadToken(precedingTrivia, length + 2, ERRID.ERR_IllegalCharConstant) End If End If End If ' the double quote was a valid string terminator. length += 1 Dim spelling = GetTextNotInterned(length) followingTrivia = ScanSingleLineTrivia() ' NATURAL TEXT, NO INTERNING Dim result As SyntaxToken = SyntaxFactory.StringLiteralToken(spelling, GetScratchText(scratch), precedingTrivia.Node, followingTrivia.Node) If haveNewLine Then result = Parser.CheckFeatureAvailability(Feature.MultilineStringLiterals, result, Options.LanguageVersion) End If Return result ElseIf IsNewLine(ch) Then If _isScanningDirective Then Exit While End If haveNewLine = True End If scratch.Append(ch) length += 1 End While ' CC has trouble to prove this after the loop Debug.Assert(CanGet(length - 1)) '// The literal does not have an explicit termination. ' DIFFERENT: here in IDE we used to report string token marked as unterminated Dim sp = GetTextNotInterned(length) followingTrivia = ScanSingleLineTrivia() Dim strTk = SyntaxFactory.StringLiteralToken(sp, GetScratchText(scratch), precedingTrivia.Node, followingTrivia.Node) Dim StrTkErr = strTk.SetDiagnostics({ErrorFactory.ErrorInfo(ERRID.ERR_UnterminatedStringLiteral)}) Debug.Assert(StrTkErr IsNot Nothing) Return DirectCast(StrTkErr, SyntaxToken) End Function Friend Shared Function TryIdentifierAsContextualKeyword(id As IdentifierTokenSyntax, ByRef k As SyntaxKind) As Boolean Debug.Assert(id IsNot Nothing) If id.PossibleKeywordKind <> SyntaxKind.IdentifierToken Then k = id.PossibleKeywordKind Return True End If Return False End Function ''' <summary> ''' Try to convert an Identifier to a Keyword. Called by the parser when it wants to force ''' an identifier to be a keyword. ''' </summary> Friend Function TryIdentifierAsContextualKeyword(id As IdentifierTokenSyntax, ByRef k As KeywordSyntax) As Boolean Debug.Assert(id IsNot Nothing) Dim kind As SyntaxKind = SyntaxKind.IdentifierToken If TryIdentifierAsContextualKeyword(id, kind) Then k = MakeKeyword(id) Return True End If Return False End Function Friend Function TryTokenAsContextualKeyword(t As SyntaxToken, ByRef k As KeywordSyntax) As Boolean If t Is Nothing Then Return False End If If t.Kind = SyntaxKind.IdentifierToken Then Return TryIdentifierAsContextualKeyword(DirectCast(t, IdentifierTokenSyntax), k) End If Return False End Function Friend Shared Function TryTokenAsKeyword(t As SyntaxToken, ByRef kind As SyntaxKind) As Boolean If t Is Nothing Then Return False End If If t.IsKeyword Then kind = t.Kind Return True End If If t.Kind = SyntaxKind.IdentifierToken Then Return TryIdentifierAsContextualKeyword(DirectCast(t, IdentifierTokenSyntax), kind) End If Return False End Function Friend Shared Function IsContextualKeyword(t As SyntaxToken, ParamArray kinds As SyntaxKind()) As Boolean Dim kind As SyntaxKind = Nothing If TryTokenAsKeyword(t, kind) Then Return Array.IndexOf(kinds, kind) >= 0 End If Return False End Function Private Function IsIdentifierStartCharacter(c As Char) As Boolean Return (_isScanningForExpressionCompiler AndAlso c = "$"c) OrElse SyntaxFacts.IsIdentifierStartCharacter(c) End Function Private Function CheckFeatureAvailability(token As SyntaxToken, feature As Feature) As SyntaxToken If CheckFeatureAvailability(feature) Then Return token End If Dim requiredVersion = New VisualBasicRequiredLanguageVersion(feature.GetLanguageVersion()) Dim errorInfo = ErrorFactory.ErrorInfo(ERRID.ERR_LanguageVersion, _options.LanguageVersion.GetErrorName(), ErrorFactory.ErrorInfo(feature.GetResourceId()), requiredVersion) Return DirectCast(token.AddError(errorInfo), SyntaxToken) End Function Friend Function CheckFeatureAvailability(feature As Feature) As Boolean Return CheckFeatureAvailability(Me.Options, feature) End Function Private Shared Function CheckFeatureAvailability(parseOptions As VisualBasicParseOptions, feature As Feature) As Boolean Dim featureFlag = feature.GetFeatureFlag() If featureFlag IsNot Nothing Then Return parseOptions.Features.ContainsKey(featureFlag) End If Dim required = feature.GetLanguageVersion() Dim actual = parseOptions.LanguageVersion Return CInt(required) <= CInt(actual) End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Test/Emit/PDB/PDBSyncLockTests.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 PDBSyncLockTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SyncLockWithThrow() Dim source = <compilation> <file> Option Strict On Imports System Class C1 Public Shared Function Something(x As Integer) As C1 Return New C1() End Function Public Shared Sub Main() Try Dim lock As New Object() SyncLock Something(12) Dim x As Integer = 23 Throw New exception() Console.WriteLine("Inside SyncLock.") End SyncLock Catch End Try End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) Dim v = CompileAndVerify(compilation) v.VerifyIL("C1.Main", " { // Code size 69 (0x45) .maxstack 2 .locals init (Object V_0, //lock Object V_1, Boolean V_2, Integer V_3) //x -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""Sub Object..ctor()"" IL_0007: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_000c: stloc.0 -IL_000d: nop -IL_000e: ldc.i4.s 12 IL_0010: call ""Function C1.Something(Integer) As C1"" IL_0015: stloc.1 IL_0016: ldc.i4.0 IL_0017: stloc.2 .try { IL_0018: ldloc.1 IL_0019: ldloca.s V_2 IL_001b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0020: nop -IL_0021: ldc.i4.s 23 IL_0023: stloc.3 -IL_0024: newobj ""Sub System.Exception..ctor()"" IL_0029: throw } finally { ~IL_002a: ldloc.2 IL_002b: brfalse.s IL_0034 IL_002d: ldloc.1 IL_002e: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0033: nop -IL_0034: nop IL_0035: endfinally } } catch System.Exception { ~IL_0036: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" -IL_003b: nop IL_003c: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0041: leave.s IL_0043 } -IL_0043: nop -IL_0044: ret }", sequencePoints:="C1.Main") v.VerifyPdb("C1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="21"/> <slot kind="3" offset="55"/> <slot kind="2" offset="55"/> <slot kind="0" offset="99"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="29" document="1"/> <entry offset="0x1" startLine="11" startColumn="9" endLine="11" endColumn="12" document="1"/> <entry offset="0x2" startLine="12" startColumn="17" endLine="12" endColumn="37" document="1"/> <entry offset="0xd" startLine="13" startColumn="13" endLine="13" endColumn="35" document="1"/> <entry offset="0xe" startLine="13" startColumn="22" endLine="13" endColumn="35" document="1"/> <entry offset="0x21" startLine="14" startColumn="21" endLine="14" endColumn="38" document="1"/> <entry offset="0x24" startLine="15" startColumn="17" endLine="15" endColumn="38" document="1"/> <entry offset="0x2a" hidden="true" document="1"/> <entry offset="0x34" startLine="17" startColumn="13" endLine="17" endColumn="25" document="1"/> <entry offset="0x36" hidden="true" document="1"/> <entry offset="0x3b" startLine="18" startColumn="9" endLine="18" endColumn="14" document="1"/> <entry offset="0x43" startLine="19" startColumn="9" endLine="19" endColumn="16" document="1"/> <entry offset="0x44" startLine="20" startColumn="5" endLine="20" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x45"> <importsforward declaringType="C1" methodName="Something" parameterNames="x"/> <scope startOffset="0x2" endOffset="0x35"> <local name="lock" il_index="0" il_start="0x2" il_end="0x35" attributes="0"/> <scope startOffset="0x21" endOffset="0x29"> <local name="x" il_index="3" il_start="0x21" il_end="0x29" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) 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 PDBSyncLockTests Inherits BasicTestBase <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.NativePdbRequiresDesktop)> Public Sub SyncLockWithThrow() Dim source = <compilation> <file> Option Strict On Imports System Class C1 Public Shared Function Something(x As Integer) As C1 Return New C1() End Function Public Shared Sub Main() Try Dim lock As New Object() SyncLock Something(12) Dim x As Integer = 23 Throw New exception() Console.WriteLine("Inside SyncLock.") End SyncLock Catch End Try End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithMscorlib40AndVBRuntime(source, TestOptions.DebugExe) Dim v = CompileAndVerify(compilation) v.VerifyIL("C1.Main", " { // Code size 69 (0x45) .maxstack 2 .locals init (Object V_0, //lock Object V_1, Boolean V_2, Integer V_3) //x -IL_0000: nop .try { -IL_0001: nop -IL_0002: newobj ""Sub Object..ctor()"" IL_0007: call ""Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"" IL_000c: stloc.0 -IL_000d: nop -IL_000e: ldc.i4.s 12 IL_0010: call ""Function C1.Something(Integer) As C1"" IL_0015: stloc.1 IL_0016: ldc.i4.0 IL_0017: stloc.2 .try { IL_0018: ldloc.1 IL_0019: ldloca.s V_2 IL_001b: call ""Sub System.Threading.Monitor.Enter(Object, ByRef Boolean)"" IL_0020: nop -IL_0021: ldc.i4.s 23 IL_0023: stloc.3 -IL_0024: newobj ""Sub System.Exception..ctor()"" IL_0029: throw } finally { ~IL_002a: ldloc.2 IL_002b: brfalse.s IL_0034 IL_002d: ldloc.1 IL_002e: call ""Sub System.Threading.Monitor.Exit(Object)"" IL_0033: nop -IL_0034: nop IL_0035: endfinally } } catch System.Exception { ~IL_0036: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.SetProjectError(System.Exception)"" -IL_003b: nop IL_003c: call ""Sub Microsoft.VisualBasic.CompilerServices.ProjectData.ClearProjectError()"" IL_0041: leave.s IL_0043 } -IL_0043: nop -IL_0044: ret }", sequencePoints:="C1.Main") v.VerifyPdb("C1.Main", <symbols> <files> <file id="1" name="" language="VB"/> </files> <entryPoint declaringType="C1" methodName="Main"/> <methods> <method containingType="C1" name="Main"> <customDebugInfo> <encLocalSlotMap> <slot kind="0" offset="21"/> <slot kind="3" offset="55"/> <slot kind="2" offset="55"/> <slot kind="0" offset="99"/> </encLocalSlotMap> </customDebugInfo> <sequencePoints> <entry offset="0x0" startLine="10" startColumn="5" endLine="10" endColumn="29" document="1"/> <entry offset="0x1" startLine="11" startColumn="9" endLine="11" endColumn="12" document="1"/> <entry offset="0x2" startLine="12" startColumn="17" endLine="12" endColumn="37" document="1"/> <entry offset="0xd" startLine="13" startColumn="13" endLine="13" endColumn="35" document="1"/> <entry offset="0xe" startLine="13" startColumn="22" endLine="13" endColumn="35" document="1"/> <entry offset="0x21" startLine="14" startColumn="21" endLine="14" endColumn="38" document="1"/> <entry offset="0x24" startLine="15" startColumn="17" endLine="15" endColumn="38" document="1"/> <entry offset="0x2a" hidden="true" document="1"/> <entry offset="0x34" startLine="17" startColumn="13" endLine="17" endColumn="25" document="1"/> <entry offset="0x36" hidden="true" document="1"/> <entry offset="0x3b" startLine="18" startColumn="9" endLine="18" endColumn="14" document="1"/> <entry offset="0x43" startLine="19" startColumn="9" endLine="19" endColumn="16" document="1"/> <entry offset="0x44" startLine="20" startColumn="5" endLine="20" endColumn="12" document="1"/> </sequencePoints> <scope startOffset="0x0" endOffset="0x45"> <importsforward declaringType="C1" methodName="Something" parameterNames="x"/> <scope startOffset="0x2" endOffset="0x35"> <local name="lock" il_index="0" il_start="0x2" il_end="0x35" attributes="0"/> <scope startOffset="0x21" endOffset="0x29"> <local name="x" il_index="3" il_start="0x21" il_end="0x29" attributes="0"/> </scope> </scope> </scope> </method> </methods> </symbols>) End Sub End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/AbstractKeyedCodeElement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { /// <summary> /// This is the base class of all code elements identified by a SyntaxNodeKey. /// </summary> public abstract class AbstractKeyedCodeElement : AbstractCodeElement { private SyntaxNodeKey _nodeKey; private readonly string _name; internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKind) { _nodeKey = nodeKey; _name = null; } // This constructor is called for "unknown" code elements. internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _nodeKey = new SyntaxNodeKey(name, -1); _name = name; } internal SyntaxNodeKey NodeKey { get { return _nodeKey; } } internal bool IsUnknown { get { return _nodeKey.Ordinal == -1; } } internal override SyntaxNode LookupNode() => CodeModelService.LookupNode(_nodeKey, GetSyntaxTree()); internal override bool TryLookupNode(out SyntaxNode node) => CodeModelService.TryLookupNode(_nodeKey, GetSyntaxTree(), out node); /// <summary> /// This function re-acquires the key for this code element using the given syntax path. /// </summary> internal void ReacquireNodeKey(SyntaxPath syntaxPath, CancellationToken cancellationToken) { Debug.Assert(syntaxPath != null); if (!syntaxPath.TryResolve(GetSyntaxTree(), cancellationToken, out SyntaxNode node)) { throw Exceptions.ThrowEFail(); } var newNodeKey = CodeModelService.GetNodeKey(node); FileCodeModel.UpdateCodeElementNodeKey(this, _nodeKey, newNodeKey); _nodeKey = newNodeKey; } protected void UpdateNodeAndReacquireNodeKey<T>(Action<SyntaxNode, T> updater, T value, bool trackKinds = true) { FileCodeModel.EnsureEditor(() => { // Sometimes, changing an element can result in needing to update its node key. var node = LookupNode(); var nodePath = new SyntaxPath(node, trackKinds); updater(node, value); ReacquireNodeKey(nodePath, CancellationToken.None); }); } protected override Document DeleteCore(Document document) { var result = base.DeleteCore(document); FileCodeModel.OnCodeElementDeleted(_nodeKey); return result; } protected override string GetName() { if (IsUnknown) { return _name; } return base.GetName(); } protected override void SetName(string value) { FileCodeModel.EnsureEditor(() => { var nodeKeyValidation = new NodeKeyValidation(); nodeKeyValidation.AddFileCodeModel(this.FileCodeModel); var node = LookupNode(); FileCodeModel.UpdateName(node, value); nodeKeyValidation.RestoreKeys(); }); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Diagnostics; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { /// <summary> /// This is the base class of all code elements identified by a SyntaxNodeKey. /// </summary> public abstract class AbstractKeyedCodeElement : AbstractCodeElement { private SyntaxNodeKey _nodeKey; private readonly string _name; internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKind) { _nodeKey = nodeKey; _name = null; } // This constructor is called for "unknown" code elements. internal AbstractKeyedCodeElement( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind) { _nodeKey = new SyntaxNodeKey(name, -1); _name = name; } internal SyntaxNodeKey NodeKey { get { return _nodeKey; } } internal bool IsUnknown { get { return _nodeKey.Ordinal == -1; } } internal override SyntaxNode LookupNode() => CodeModelService.LookupNode(_nodeKey, GetSyntaxTree()); internal override bool TryLookupNode(out SyntaxNode node) => CodeModelService.TryLookupNode(_nodeKey, GetSyntaxTree(), out node); /// <summary> /// This function re-acquires the key for this code element using the given syntax path. /// </summary> internal void ReacquireNodeKey(SyntaxPath syntaxPath, CancellationToken cancellationToken) { Debug.Assert(syntaxPath != null); if (!syntaxPath.TryResolve(GetSyntaxTree(), cancellationToken, out SyntaxNode node)) { throw Exceptions.ThrowEFail(); } var newNodeKey = CodeModelService.GetNodeKey(node); FileCodeModel.UpdateCodeElementNodeKey(this, _nodeKey, newNodeKey); _nodeKey = newNodeKey; } protected void UpdateNodeAndReacquireNodeKey<T>(Action<SyntaxNode, T> updater, T value, bool trackKinds = true) { FileCodeModel.EnsureEditor(() => { // Sometimes, changing an element can result in needing to update its node key. var node = LookupNode(); var nodePath = new SyntaxPath(node, trackKinds); updater(node, value); ReacquireNodeKey(nodePath, CancellationToken.None); }); } protected override Document DeleteCore(Document document) { var result = base.DeleteCore(document); FileCodeModel.OnCodeElementDeleted(_nodeKey); return result; } protected override string GetName() { if (IsUnknown) { return _name; } return base.GetName(); } protected override void SetName(string value) { FileCodeModel.EnsureEditor(() => { var nodeKeyValidation = new NodeKeyValidation(); nodeKeyValidation.AddFileCodeModel(this.FileCodeModel); var node = LookupNode(); FileCodeModel.UpdateName(node, value); nodeKeyValidation.RestoreKeys(); }); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/VisualBasicTest/AddAnonymousTypeMemberName/AddAnonymousTypeMemberNameTests.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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.AddAnonymousTypeMemberName Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAnonymousTypeMemberName Public Class AddAnonymousTypeMemberNameTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(Workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicAddAnonymousTypeMemberNameCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function Test1() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {[||]me.Equals(1)} end sub end class", " class C sub M() dim v = new with {.{|Rename:V|} = me.Equals(1)} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestExistingName1() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {.V = 1, [||]me.Equals(1)} end sub end class", " class C sub M() dim v = new with {.V = 1, .{|Rename:V1|} = me.Equals(1)} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestExistingName2() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {.v = 1, [||]me.Equals(1)} end sub end class", " class C sub M() dim v = new with {.v = 1, .{|Rename:V1|} = me.Equals(1)} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestFixAll1() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.ToString() + 1}} end sub end class", " class C sub M() dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestFixAll2() As Task Await TestInRegularAndScript1Async( " class C { sub M() { dim v = new with {new with {{|FixAllInDocument:|}me.Equals(1), me.ToString() + 1}} } end class", " class C { sub M() { dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}} } end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestFixAll3() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.Equals(2)}} end sub end class", " class C sub M() dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.Equals(2)}} end sub end class") 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.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.AddAnonymousTypeMemberName Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.AddAnonymousTypeMemberName Public Class AddAnonymousTypeMemberNameTests Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest Friend Overrides Function CreateDiagnosticProviderAndFixer(Workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider) Return (Nothing, New VisualBasicAddAnonymousTypeMemberNameCodeFixProvider()) End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function Test1() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {[||]me.Equals(1)} end sub end class", " class C sub M() dim v = new with {.{|Rename:V|} = me.Equals(1)} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestExistingName1() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {.V = 1, [||]me.Equals(1)} end sub end class", " class C sub M() dim v = new with {.V = 1, .{|Rename:V1|} = me.Equals(1)} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestExistingName2() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {.v = 1, [||]me.Equals(1)} end sub end class", " class C sub M() dim v = new with {.v = 1, .{|Rename:V1|} = me.Equals(1)} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestFixAll1() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.ToString() + 1}} end sub end class", " class C sub M() dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}} end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestFixAll2() As Task Await TestInRegularAndScript1Async( " class C { sub M() { dim v = new with {new with {{|FixAllInDocument:|}me.Equals(1), me.ToString() + 1}} } end class", " class C { sub M() { dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.ToString() + 1}} } end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsAddAnonymousTypeMemberName)> Public Async Function TestFixAll3() As Task Await TestInRegularAndScript1Async( " class C sub M() dim v = new with {{|FixAllInDocument:|}new with {me.Equals(1), me.Equals(2)}} end sub end class", " class C sub M() dim v = new with {.P = new with {.V = me.Equals(1), .V1 = me.Equals(2)}} end sub end class") End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/VisualBasicTest/SignatureHelp/ConditionalExpressionSignatureHelpProviderTests.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 BinaryConditionalExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(BinaryConditionalExpressionSignatureHelpProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForIf() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = If($$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.expression}, {VBWorkspaceResources.expressionIfNothing}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing, VBWorkspaceResources.Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing, currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.condition} As Boolean, {VBWorkspaceResources.expressionIfTrue}, {VBWorkspaceResources.expressionIfFalse}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse, VBWorkspaceResources.The_expression_to_evaluate, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForIfAfterComma() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = If(True, $$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.expression}, {VBWorkspaceResources.expressionIfNothing}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing, VBWorkspaceResources.Evaluated_and_returned_if_expression_evaluates_to_Nothing, currentParameterIndex:=1)) expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.condition} As Boolean, {VBWorkspaceResources.expressionIfTrue}, {VBWorkspaceResources.expressionIfFalse}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse, VBWorkspaceResources.Evaluated_and_returned_if_condition_evaluates_to_True, currentParameterIndex:=1)) 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 BinaryConditionalExpressionSignatureHelpProviderTests Inherits AbstractVisualBasicSignatureHelpProviderTests Friend Overrides Function GetSignatureHelpProviderType() As Type Return GetType(BinaryConditionalExpressionSignatureHelpProvider) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForIf() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = If($$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.expression}, {VBWorkspaceResources.expressionIfNothing}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing, VBWorkspaceResources.Returned_if_it_evaluates_to_a_reference_or_nullable_type_that_is_not_Nothing, currentParameterIndex:=0)) expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.condition} As Boolean, {VBWorkspaceResources.expressionIfTrue}, {VBWorkspaceResources.expressionIfFalse}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse, VBWorkspaceResources.The_expression_to_evaluate, currentParameterIndex:=0)) Await TestAsync(markup, expectedOrderedItems) End Function <Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)> Public Async Function TestInvocationForIfAfterComma() As Task Dim markup = <a><![CDATA[ Class C Sub Goo() Dim x = If(True, $$ End Sub End Class ]]></a>.Value Dim expectedOrderedItems = New List(Of SignatureHelpTestItem)() expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.expression}, {VBWorkspaceResources.expressionIfNothing}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_expression_evaluates_to_a_reference_or_Nullable_value_that_is_not_Nothing_the_function_returns_that_value_Otherwise_it_calculates_and_returns_expressionIfNothing, VBWorkspaceResources.Evaluated_and_returned_if_expression_evaluates_to_Nothing, currentParameterIndex:=1)) expectedOrderedItems.Add(New SignatureHelpTestItem( $"If({VBWorkspaceResources.condition} As Boolean, {VBWorkspaceResources.expressionIfTrue}, {VBWorkspaceResources.expressionIfFalse}) As {VBWorkspaceResources.result}", VBWorkspaceResources.If_condition_returns_True_the_function_calculates_and_returns_expressionIfTrue_Otherwise_it_returns_expressionIfFalse, VBWorkspaceResources.Evaluated_and_returned_if_condition_evaluates_to_True, currentParameterIndex:=1)) Await TestAsync(markup, expectedOrderedItems) End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/Core/Portable/Symbols/SymbolVisitor`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 { public abstract class SymbolVisitor<TResult> { public virtual TResult? Visit(ISymbol? symbol) { return symbol == null ? default(TResult?) : symbol.Accept(this); } public virtual TResult? DefaultVisit(ISymbol symbol) { return default(TResult?); } public virtual TResult? VisitAlias(IAliasSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitArrayType(IArrayTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitAssembly(IAssemblySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitDiscard(IDiscardSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitDynamicType(IDynamicTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitEvent(IEventSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitField(IFieldSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitLabel(ILabelSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitLocal(ILocalSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitMethod(IMethodSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitModule(IModuleSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitNamedType(INamedTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitNamespace(INamespaceSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitParameter(IParameterSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitPointerType(IPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitProperty(IPropertySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitRangeVariable(IRangeVariableSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitTypeParameter(ITypeParameterSymbol symbol) { return DefaultVisit(symbol); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { public abstract class SymbolVisitor<TResult> { public virtual TResult? Visit(ISymbol? symbol) { return symbol == null ? default(TResult?) : symbol.Accept(this); } public virtual TResult? DefaultVisit(ISymbol symbol) { return default(TResult?); } public virtual TResult? VisitAlias(IAliasSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitArrayType(IArrayTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitAssembly(IAssemblySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitDiscard(IDiscardSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitDynamicType(IDynamicTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitEvent(IEventSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitField(IFieldSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitLabel(ILabelSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitLocal(ILocalSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitMethod(IMethodSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitModule(IModuleSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitNamedType(INamedTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitNamespace(INamespaceSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitParameter(IParameterSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitPointerType(IPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitProperty(IPropertySymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitRangeVariable(IRangeVariableSymbol symbol) { return DefaultVisit(symbol); } public virtual TResult? VisitTypeParameter(ITypeParameterSymbol symbol) { return DefaultVisit(symbol); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Test/Syntax/Parsing/StatementAttributeParsingTests.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.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StatementAttributes)] public class StatementAttributeParsingTests : ParsingTests { public StatementAttributeParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void AttributeOnBlock() { var test = UsingTree(@" class C { void Goo() { [A]{} } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnEmptyStatement() { var test = UsingTree(@" class C { void Goo() { [A]; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EmptyStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnLabeledStatement() { var test = UsingTree(@" class C { void Goo() { [A] bar: Goo(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LabeledStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierToken, "bar"); N(SyntaxKind.ColonToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Goo"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (7,9): warning CS0164: This label has not been referenced // bar: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "bar").WithLocation(7, 9)); } [Fact] public void AttributeOnGotoStatement() { var test = UsingTree(@" class C { void Goo() { [A] goto bar; bar: Goo(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GotoStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.GotoKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "bar"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.LabeledStatement); { N(SyntaxKind.IdentifierToken, "bar"); N(SyntaxKind.ColonToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Goo"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnBreakStatement() { var test = UsingTree(@" class C { void Goo() { while (true) { [A] break; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.WhileStatement); { N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.BreakStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13)); } [Fact] public void AttributeOnContinueStatement() { var test = UsingTree(@" class C { void Goo() { while (true) { [A] continue; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.WhileStatement); { N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ContinueStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ContinueKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13)); } [Fact] public void AttributeOnReturn() { var test = UsingTree(@" class C { void Goo() { [A]return; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnThrow() { var test = UsingTree(@" class C { void Goo() { [A]throw; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ThrowStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ThrowKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]throw; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // [A]throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(6, 12)); } [Fact] public void AttributeOnYieldReturn() { var test = UsingTree(@" class C { void Goo() { [A]yield return 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.YieldReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.YieldKeyword); N(SyntaxKind.ReturnKeyword); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type // void Goo() Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10), // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnYieldBreak() { var test = UsingTree(@" class C { void Goo() { [A]yield return 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.YieldReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.YieldKeyword); N(SyntaxKind.ReturnKeyword); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type // void Goo() Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10), // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnNakedYield() { var test = UsingTree(@" class C { void Goo() { [A]yield } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "yield"); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]yield Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0103: The name 'yield' does not exist in the current context // [A]yield Diagnostic(ErrorCode.ERR_NameNotInContext, "yield").WithArguments("yield").WithLocation(6, 12), // (6,17): error CS1002: ; expected // [A]yield Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 17)); } [Fact] public void AttributeOnWhileStatement() { var test = UsingTree(@" class C { void Goo() { [A]while (true); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.WhileStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnDoStatement() { var test = UsingTree(@" class C { void Goo() { [A]do { } while (true); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.DoStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DoKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnForStatement() { var test = UsingTree(@" class C { void Goo() { [A]for (;;) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnNormalForEachStatement() { var test = UsingTree(@" class C { void Goo(string[] vals) { [A]foreach (var v in vals) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.IdentifierToken, "v"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnForEachVariableStatement() { var test = UsingTree(@" class C { void Goo((int, string)[] vals) { [A]foreach (var (i, s) in vals) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnUsingStatement() { var test = UsingTree(@" class C { void Goo() { [A]using (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnAwaitUsingStatement1() { var test = UsingTree(@" class C { void Goo() { [A]await using (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using (null) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12), // (6,12): 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'. // [A]await using (null) { } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12)); } [Fact] public void AttributeOnAwaitUsingStatement2() { var test = UsingTree(@" class C { async void Goo() { [A]await using (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using (null) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12)); } [Fact] public void AttributeOnFixedStatement() { var test = UsingTree(@" class C { unsafe void Goo(int[] vals) { [A]fixed (int* p = vals) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FixedStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.FixedKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "p"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "vals"); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Goo(int[] vals) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Goo").WithLocation(4, 17), // (6,9): error CS7014: Attributes are not valid in this context. // [A]fixed (int* p = vals) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnCheckedStatement() { var test = UsingTree(@" class C { void Goo() { [A]checked { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CheckedStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.CheckedKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnCheckedBlock() { var test = UsingTree(@" class C { void Goo() { checked [A]{ } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CheckedStatement); { N(SyntaxKind.CheckedKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,17): error CS7014: Attributes are not valid in this context. // checked [A]{ } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17)); } [Fact] public void AttributeOnUncheckedStatement() { var test = UsingTree(@" class C { void Goo() { [A]unchecked { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UncheckedStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UncheckedKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnUnsafeStatement() { var test = UsingTree(@" class C { void Goo() { [A]unsafe { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UnsafeStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]unsafe { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0227: Unsafe code may only appear if compiling with /unsafe // [A]unsafe { } Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(6, 12)); } [Fact] public void AttributeOnUnsafeBlock() { var test = UsingTree(@" class C { void Goo() { unsafe [A]{ } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.ArrayType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS0106: The modifier 'unsafe' is not valid for this item // unsafe [A]{ } Diagnostic(ErrorCode.ERR_BadMemberFlag, "unsafe").WithArguments("unsafe").WithLocation(6, 9), // (6,16): error CS1031: Type expected // unsafe [A]{ } Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(6, 16), // (6,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // unsafe [A]{ } Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[A]").WithLocation(6, 16), // (6,17): error CS0103: The name 'A' does not exist in the current context // unsafe [A]{ } Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(6, 17), // (6,19): error CS1001: Identifier expected // unsafe [A]{ } Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(6, 19), // (6,19): error CS1002: ; expected // unsafe [A]{ } Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 19)); } [Fact] public void AttributeOnLockStatement() { var test = UsingTree(@" class C { void Goo() { [A]lock (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LockStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.LockKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnIfStatement() { var test = UsingTree(@" class C { void Goo() { [A]if (true) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnSwitchStatement() { var test = UsingTree(@" class C { void Goo() { [A]switch (0) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]switch (0) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,23): warning CS1522: Empty switch block // [A]switch (0) { } Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(6, 23)); } [Fact] public void AttributeOnStatementInSwitchSection() { var test = UsingTree(@" class C { void Goo() { switch (0) { default: [A]return; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.DefaultSwitchLabel); { N(SyntaxKind.DefaultKeyword); N(SyntaxKind.ColonToken); } N(SyntaxKind.ReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (9,17): error CS7014: Attributes are not valid in this context. // [A]return; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(9, 17)); } [Fact] public void AttributeOnStatementAboveCase() { var test = UsingTree(@" class C { void Goo() { switch (0) { [A] case 0: return; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (7,9): warning CS1522: Empty switch block // { Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9), // (7,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10), // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13), // (8,16): error CS1525: Invalid expression term 'case' // [A] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("case").WithLocation(8, 16), // (8,16): error CS1002: ; expected // [A] Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16), // (8,16): error CS1513: } expected // [A] Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 16), // (9,19): error CS1002: ; expected // case 0: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 19), // (9,19): error CS1513: } expected // case 0: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 19), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1)); } [Fact] public void AttributeOnStatementAboveDefaultCase() { var test = UsingTree(@" class C { void Goo() { switch (0) { [A] default: return; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DefaultLiteralExpression); { N(SyntaxKind.DefaultKeyword); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (7,9): warning CS1522: Empty switch block // { Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9), // (7,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10), // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13), // (9,13): error CS8716: There is no target type for the default literal. // default: Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 13), // (9,20): error CS1002: ; expected // default: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 20), // (9,20): error CS1513: } expected // default: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 20), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1)); } [Fact] public void AttributeOnTryStatement() { var test = UsingTree(@" class C { void Goo() { [A]try { } finally { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]try { } finally { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnTryBlock() { var test = UsingTree(@" class C { void Goo() { try [A] { } finally { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,13): error CS7014: Attributes are not valid in this context. // try [A] { } finally { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 13)); } [Fact] public void AttributeOnFinally() { var test = UsingTree(@" class C { void Goo() { try { } [A] finally { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } M(SyntaxKind.FinallyClause); { M(SyntaxKind.FinallyKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.TryStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } M(SyntaxKind.TryKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,15): error CS1524: Expected catch or finally // try { } [A] finally { } Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15), // (6,17): error CS7014: Attributes are not valid in this context. // try { } [A] finally { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17), // (6,21): error CS1003: Syntax error, 'try' expected // try { } [A] finally { } Diagnostic(ErrorCode.ERR_SyntaxError, "finally").WithArguments("try", "finally").WithLocation(6, 21), // (6,21): error CS1514: { expected // try { } [A] finally { } Diagnostic(ErrorCode.ERR_LbraceExpected, "finally").WithLocation(6, 21), // (6,21): error CS1513: } expected // try { } [A] finally { } Diagnostic(ErrorCode.ERR_RbraceExpected, "finally").WithLocation(6, 21)); } [Fact] public void AttributeOnFinallyBlock() { var test = UsingTree(@" class C { void Goo() { try { } finally [A] { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,25): error CS7014: Attributes are not valid in this context. // try { } finally [A] { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 25)); } [Fact] public void AttributeOnCatch() { var test = UsingTree(@" class C { void Goo() { try { } [A] catch { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } M(SyntaxKind.FinallyClause); { M(SyntaxKind.FinallyKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.TryStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } M(SyntaxKind.TryKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CatchClause); { N(SyntaxKind.CatchKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,15): error CS1524: Expected catch or finally // try { } [A] catch { } Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15), // (6,17): error CS7014: Attributes are not valid in this context. // try { } [A] catch { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17), // (6,21): error CS1003: Syntax error, 'try' expected // try { } [A] catch { } Diagnostic(ErrorCode.ERR_SyntaxError, "catch").WithArguments("try", "catch").WithLocation(6, 21), // (6,21): error CS1514: { expected // try { } [A] catch { } Diagnostic(ErrorCode.ERR_LbraceExpected, "catch").WithLocation(6, 21), // (6,21): error CS1513: } expected // try { } [A] catch { } Diagnostic(ErrorCode.ERR_RbraceExpected, "catch").WithLocation(6, 21)); } [Fact] public void AttributeOnCatchBlock() { var test = UsingTree(@" class C { void Goo() { try { } catch [A] { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CatchClause); { N(SyntaxKind.CatchKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,23): error CS7014: Attributes are not valid in this context. // try { } catch [A] { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 23)); } [Fact] public void AttributeOnEmbeddedStatement() { var test = UsingTree(@" class C { void Goo() { if (true) [A]return; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,19): error CS7014: Attributes are not valid in this context. // if (true) [A]return; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 19)); } [Fact] public void AttributeOnExpressionStatement_AnonymousMethod_NoParameters() { var test = UsingTree(@" class C { void Goo() { [A]delegate { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]delegate { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,24): error CS1002: ; expected // [A]delegate { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 24)); } [Fact] public void AttributeOnExpressionStatement_AnonymousMethod_NoBody() { var test = UsingTree(@" class C { void Goo() { [A]delegate } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]delegate Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,20): error CS1514: { expected // [A]delegate Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(6, 20), // (6,20): error CS1002: ; expected // [A]delegate Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20)); } [Fact] public void AttributeOnExpressionStatement_AnonymousMethod_Parameters() { var test = UsingTree(@" class C { void Goo() { [A]delegate () { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]delegate () { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]delegate () { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "delegate () { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Lambda_NoParameters() { var test = UsingTree(@" class C { void Goo() { [A]() => { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]() => { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]() => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "() => { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Lambda_Parameters1() { var test = UsingTree(@" class C { void Goo() { [A](int i) => { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A](int i) => { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A](int i) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(int i) => { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Lambda_Parameters2() { var test = UsingTree(@" class C { void Goo() { [A]i => { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]i => { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]i => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "i => { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_AnonymousObject() { var test = UsingTree(@" class C { void Goo() { [A]new { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]new { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "new { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ArrayCreation() { var test = UsingTree(@" class C { void Goo() { [A]new int[] { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new int[] { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]new int[] { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "new int[] { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_AnonymousArrayCreation() { var test = UsingTree(@" class C { void Goo() { [A]new [] { 0 }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ImplicitArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new [] { 0 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]new [] { 0 }; Diagnostic(ErrorCode.ERR_IllegalStatement, "new [] { 0 }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Assignment() { var test = UsingTree(@" class C { void Goo(int a) { [A]a = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_CompoundAssignment() { var test = UsingTree(@" class C { void Goo(int a) { [A]a += 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AddAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a += 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_AwaitExpression_NonAsyncContext() { var test = UsingTree(@" class C { void Goo() { [A]await a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "await"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0246: The type or namespace name 'await' could not be found (are you missing a using directive or an assembly reference?) // [A]await a; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "await").WithArguments("await").WithLocation(6, 12), // (6,18): warning CS0168: The variable 'a' is declared but never used // [A]await a; Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 18)); } [Fact] public void AttributeOnExpressionStatement_AwaitExpression_AsyncContext() { var test = UsingTree(@" class C { async void Goo() { [A]await a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitExpression); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,18): error CS0103: The name 'a' does not exist in the current context // [A]await a; Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 18)); } [Fact] public void AttributeOnExpressionStatement_BinaryExpression() { var test = UsingTree(@" class C { void Goo(int a) { [A]a + a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a + a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a + a; Diagnostic(ErrorCode.ERR_IllegalStatement, "a + a").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_CastExpression() { var test = UsingTree(@" class C { void Goo(int a) { [A](object)a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A](object)a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A](object)a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(object)a").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ConditionalAccess() { var test = UsingTree(@" class C { void Goo(string a) { [A]a?.ToString(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ToString"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a?.ToString(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_DefaultExpression() { var test = UsingTree(@" class C { void Goo() { [A]default(int); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DefaultExpression); { N(SyntaxKind.DefaultKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]default(int); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]default(int); Diagnostic(ErrorCode.ERR_IllegalStatement, "default(int)").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_DefaultLiteral() { var test = UsingTree(@" class C { void Goo() { [A]default; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DefaultLiteralExpression); { N(SyntaxKind.DefaultKeyword); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]default; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS8716: There is no target type for the default literal. // [A]default; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]default; Diagnostic(ErrorCode.ERR_IllegalStatement, "default").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ElementAccess() { var test = UsingTree(@" class C { void Goo(string s) { [A]s[0]; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]s[0]; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]s[0]; Diagnostic(ErrorCode.ERR_IllegalStatement, "s[0]").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ElementBinding() { var test = UsingTree(@" class C { void Goo(string s) { [A]s?[0]; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ElementBindingExpression); { N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]s?[0]; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]s?[0]; Diagnostic(ErrorCode.ERR_IllegalStatement, "s?[0]").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Invocation() { var test = UsingTree(@" class C { void Goo() { [A]Goo(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Goo"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]Goo(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_Literal() { var test = UsingTree(@" class C { void Goo() { [A]0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]0; Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_MemberAccess() { var test = UsingTree(@" class C { void Goo(int i) { [A]i.ToString; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ToString"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]i.ToString; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]i.ToString; Diagnostic(ErrorCode.ERR_IllegalStatement, "i.ToString").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ObjectCreation_Builtin() { var test = UsingTree(@" class C { void Goo() { [A]new int(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new int(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_ObjectCreation_TypeName() { var test = UsingTree(@" class C { void Goo() { [A]new System.Int32(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new System.Int32(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_Parenthesized() { var test = UsingTree(@" class C { void Goo() { [A](1); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A](1); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A](1); Diagnostic(ErrorCode.ERR_IllegalStatement, "(1)").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_PostfixUnary() { var test = UsingTree(@" class C { void Goo(int i) { [A]i++; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.PlusPlusToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]i++; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_PrefixUnary() { var test = UsingTree(@" class C { void Goo(int i) { [A]++i; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PreIncrementExpression); { N(SyntaxKind.PlusPlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]++i; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_Query() { var test = UsingTree(@" using System.Linq; class C { void Goo(string s) { [A]from c in s select c; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Linq"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (7,9): error CS7014: Attributes are not valid in this context. // [A]from c in s select c; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(7, 9), // (7,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]from c in s select c; Diagnostic(ErrorCode.ERR_IllegalStatement, "from c in s select c").WithLocation(7, 12)); } [Fact] public void AttributeOnExpressionStatement_Range1() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]a..b; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotDotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a..b; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]a..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..b").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]a..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a..b; Diagnostic(ErrorCode.ERR_IllegalStatement, "a..b").WithLocation(6, 12), // (6,15): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]a..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 15)); } [Fact] public void AttributeOnExpressionStatement_Range2() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]a..; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotDotToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a..; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]a..; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]a..; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a..; Diagnostic(ErrorCode.ERR_IllegalStatement, "a..").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Range3() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]..b; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.DotDotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]..b; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..b").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]..b; Diagnostic(ErrorCode.ERR_IllegalStatement, "..b").WithLocation(6, 12), // (6,14): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 14)); } [Fact] public void AttributeOnExpressionStatement_Range4() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]..; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.DotDotToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]..; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]..; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]..; Diagnostic(ErrorCode.ERR_IllegalStatement, "..").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Sizeof() { var test = UsingTree(@" class C { void Goo() { [A]sizeof(int); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SizeOfExpression); { N(SyntaxKind.SizeOfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]sizeof(int); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]sizeof(int); Diagnostic(ErrorCode.ERR_IllegalStatement, "sizeof(int)").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_SwitchExpression() { var test = UsingTree(@" class C { void Goo(int a) { [A]a switch { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a switch { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a switch { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "a switch { }").WithLocation(6, 12), // (6,14): 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. // [A]a switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 14), // (6,14): error CS8506: No best type was found for the switch expression. // [A]a switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 14)); } [Fact] public void AttributeOnExpressionStatement_TypeOf() { var test = UsingTree(@" class C { void Goo() { [A]typeof(int); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.TypeOfExpression); { N(SyntaxKind.TypeOfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]typeof(int); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]typeof(int); Diagnostic(ErrorCode.ERR_IllegalStatement, "typeof(int)").WithLocation(6, 12)); } [Fact] public void AttributeOnLocalDeclOrMember1() { var test = UsingTree(@" class C { void Goo() { [A]int i; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int i; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): warning CS0168: The variable 'i' is declared but never used // [A]int i; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16)); } [Fact] public void AttributeOnLocalDeclOrMember2() { var test = UsingTree(@" class C { void Goo() { [A]int i, j; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "j"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int i, j; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): warning CS0168: The variable 'i' is declared but never used // [A]int i, j; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16), // (6,19): warning CS0168: The variable 'j' is declared but never used // [A]int i, j; Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(6, 19)); } [Fact] public void AttributeOnLocalDeclOrMember3() { var test = UsingTree(@" class C { void Goo() { [A]int i = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): warning CS0219: The variable 'i' is assigned but its value is never used // [A]int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 16)); } [Fact] public void AttributeOnLocalDeclOrMember4() { var test = UsingTree(@" class C { void Goo() { [A]int this[int i] => 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): error CS1001: Identifier expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_IdentifierExpected, "this").WithLocation(6, 16), // (6,16): error CS1002: ; expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_SemicolonExpected, "this").WithLocation(6, 16), // (6,21): error CS1525: Invalid expression term 'int' // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 21), // (6,25): error CS1003: Syntax error, ',' expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_SyntaxError, "i").WithArguments(",", "").WithLocation(6, 25), // (6,25): error CS0103: The name 'i' does not exist in the current context // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 25), // (6,28): error CS1002: ; expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_SemicolonExpected, "=>").WithLocation(6, 28), // (6,28): error CS1513: } expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 28), // (6,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 31)); } [Fact] public void AttributeOnLocalDeclOrMember5() { var tree = UsingTree(@" class C { void Goo() { [A]const int i = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ConstKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(tree).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]const int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,22): warning CS0219: The variable 'i' is assigned but its value is never used // [A]const int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 22)); } [Fact] public void AccessModOnLocalDeclOrMember_01() { var test = UsingTree(@" class C { void Goo() { public extern int i = 1; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.ExternKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).VerifyDiagnostics( // (5,6): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 6), // (6,27): error CS0106: The modifier 'extern' is not valid for this item // public extern int i = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "i").WithArguments("extern").WithLocation(6, 27), // (8,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(8, 1)); } [Fact] public void AccessModOnLocalDeclOrMember_02() { var test = UsingTree(@" class C { void Goo() { extern public int i = 1; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).VerifyDiagnostics( // (6,9): error CS0106: The modifier 'extern' is not valid for this item // extern public int i = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "extern").WithArguments("extern").WithLocation(6, 9), // (6,16): error CS0106: The modifier 'public' is not valid for this item // extern public int i = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 16), // (6,27): warning CS0219: The variable 'i' is assigned but its value is never used // extern public int i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 27)); } [Fact] public void AttributeOnLocalDeclOrMember6() { var test = UsingTree(@" class C { void Goo() { [A]public int i = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]public int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0106: The modifier 'public' is not valid for this item // [A]public int i = 0; Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 12), // (6,23): warning CS0219: The variable 'i' is assigned but its value is never used // [A]public int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 23)); } [Fact] public void AttributeOnLocalDeclOrMember7() { var test = UsingTree(@" class C { void Goo(System.IDisposable d) { [A]using var i = d; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IDisposable"); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]using var i = d; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnLocalDeclOrMember8() { var test = UsingTree(@" class C { void Goo(System.IAsyncDisposable d) { [A]await using var i = d; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IAsyncDisposable"); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,21): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?) // void Goo(System.IAsyncDisposable d) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 21), // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using var i = d; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using var i = d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12), // (6,12): 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'. // [A]await using var i = d; Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12)); } [Fact] public void AttributeOnLocalDeclOrMember9() { var test = UsingTree(@" class C { async void Goo(System.IAsyncDisposable d) { [A]await using var i = d; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IAsyncDisposable"); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,27): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?) // async void Goo(System.IAsyncDisposable d) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 27), // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using var i = d; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using var i = d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12)); } [Fact] public void AttrDeclOnStatementWhereMemberExpected() { UsingTree(@" class C { [Attr] x.y(); } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.StatementAttributes)] public class StatementAttributeParsingTests : ParsingTests { public StatementAttributeParsingTests(ITestOutputHelper output) : base(output) { } [Fact] public void AttributeOnBlock() { var test = UsingTree(@" class C { void Goo() { [A]{} } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnEmptyStatement() { var test = UsingTree(@" class C { void Goo() { [A]; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EmptyStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnLabeledStatement() { var test = UsingTree(@" class C { void Goo() { [A] bar: Goo(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LabeledStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierToken, "bar"); N(SyntaxKind.ColonToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Goo"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (7,9): warning CS0164: This label has not been referenced // bar: Diagnostic(ErrorCode.WRN_UnreferencedLabel, "bar").WithLocation(7, 9)); } [Fact] public void AttributeOnGotoStatement() { var test = UsingTree(@" class C { void Goo() { [A] goto bar; bar: Goo(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GotoStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.GotoKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "bar"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.LabeledStatement); { N(SyntaxKind.IdentifierToken, "bar"); N(SyntaxKind.ColonToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Goo"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnBreakStatement() { var test = UsingTree(@" class C { void Goo() { while (true) { [A] break; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.WhileStatement); { N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.BreakStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.BreakKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13)); } [Fact] public void AttributeOnContinueStatement() { var test = UsingTree(@" class C { void Goo() { while (true) { [A] continue; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.WhileStatement); { N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ContinueStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ContinueKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13)); } [Fact] public void AttributeOnReturn() { var test = UsingTree(@" class C { void Goo() { [A]return; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnThrow() { var test = UsingTree(@" class C { void Goo() { [A]throw; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ThrowStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ThrowKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]throw; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0156: A throw statement with no arguments is not allowed outside of a catch clause // [A]throw; Diagnostic(ErrorCode.ERR_BadEmptyThrow, "throw").WithLocation(6, 12)); } [Fact] public void AttributeOnYieldReturn() { var test = UsingTree(@" class C { void Goo() { [A]yield return 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.YieldReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.YieldKeyword); N(SyntaxKind.ReturnKeyword); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type // void Goo() Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10), // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnYieldBreak() { var test = UsingTree(@" class C { void Goo() { [A]yield return 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.YieldReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.YieldKeyword); N(SyntaxKind.ReturnKeyword); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,10): error CS1624: The body of 'C.Goo()' cannot be an iterator block because 'void' is not an iterator interface type // void Goo() Diagnostic(ErrorCode.ERR_BadIteratorReturn, "Goo").WithArguments("C.Goo()", "void").WithLocation(4, 10), // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnNakedYield() { var test = UsingTree(@" class C { void Goo() { [A]yield } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "yield"); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]yield Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0103: The name 'yield' does not exist in the current context // [A]yield Diagnostic(ErrorCode.ERR_NameNotInContext, "yield").WithArguments("yield").WithLocation(6, 12), // (6,17): error CS1002: ; expected // [A]yield Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 17)); } [Fact] public void AttributeOnWhileStatement() { var test = UsingTree(@" class C { void Goo() { [A]while (true); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.WhileStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.EmptyStatement); { N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnDoStatement() { var test = UsingTree(@" class C { void Goo() { [A]do { } while (true); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.DoStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DoKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.WhileKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnForStatement() { var test = UsingTree(@" class C { void Goo() { [A]for (;;) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ForKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.SemicolonToken); N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnNormalForEachStatement() { var test = UsingTree(@" class C { void Goo(string[] vals) { [A]foreach (var v in vals) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.IdentifierToken, "v"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnForEachVariableStatement() { var test = UsingTree(@" class C { void Goo((int, string)[] vals) { [A]foreach (var (i, s) in vals) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } N(SyntaxKind.CommaToken); N(SyntaxKind.TupleElement); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ForEachVariableStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ForEachKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.ParenthesizedVariableDesignation); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CommaToken); N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnUsingStatement() { var test = UsingTree(@" class C { void Goo() { [A]using (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnAwaitUsingStatement1() { var test = UsingTree(@" class C { void Goo() { [A]await using (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using (null) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12), // (6,12): 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'. // [A]await using (null) { } Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12)); } [Fact] public void AttributeOnAwaitUsingStatement2() { var test = UsingTree(@" class C { async void Goo() { [A]await using (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UsingStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using (null) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Threading.Tasks.ValueTask' is not defined or imported // [A]await using (null) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.Threading.Tasks.ValueTask").WithLocation(6, 12)); } [Fact] public void AttributeOnFixedStatement() { var test = UsingTree(@" class C { unsafe void Goo(int[] vals) { [A]fixed (int* p = vals) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.IdentifierToken, "vals"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.FixedStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.FixedKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PointerType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.AsteriskToken); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "p"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "vals"); } } } } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,17): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe void Goo(int[] vals) Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Goo").WithLocation(4, 17), // (6,9): error CS7014: Attributes are not valid in this context. // [A]fixed (int* p = vals) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnCheckedStatement() { var test = UsingTree(@" class C { void Goo() { [A]checked { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CheckedStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.CheckedKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnCheckedBlock() { var test = UsingTree(@" class C { void Goo() { checked [A]{ } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CheckedStatement); { N(SyntaxKind.CheckedKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,17): error CS7014: Attributes are not valid in this context. // checked [A]{ } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17)); } [Fact] public void AttributeOnUncheckedStatement() { var test = UsingTree(@" class C { void Goo() { [A]unchecked { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UncheckedStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UncheckedKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnUnsafeStatement() { var test = UsingTree(@" class C { void Goo() { [A]unsafe { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.UnsafeStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]unsafe { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0227: Unsafe code may only appear if compiling with /unsafe // [A]unsafe { } Diagnostic(ErrorCode.ERR_IllegalUnsafe, "unsafe").WithLocation(6, 12)); } [Fact] public void AttributeOnUnsafeBlock() { var test = UsingTree(@" class C { void Goo() { unsafe [A]{ } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.UnsafeKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.ArrayType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } N(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS0106: The modifier 'unsafe' is not valid for this item // unsafe [A]{ } Diagnostic(ErrorCode.ERR_BadMemberFlag, "unsafe").WithArguments("unsafe").WithLocation(6, 9), // (6,16): error CS1031: Type expected // unsafe [A]{ } Diagnostic(ErrorCode.ERR_TypeExpected, "[").WithLocation(6, 16), // (6,16): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // unsafe [A]{ } Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "[A]").WithLocation(6, 16), // (6,17): error CS0103: The name 'A' does not exist in the current context // unsafe [A]{ } Diagnostic(ErrorCode.ERR_NameNotInContext, "A").WithArguments("A").WithLocation(6, 17), // (6,19): error CS1001: Identifier expected // unsafe [A]{ } Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(6, 19), // (6,19): error CS1002: ; expected // unsafe [A]{ } Diagnostic(ErrorCode.ERR_SemicolonExpected, "{").WithLocation(6, 19)); } [Fact] public void AttributeOnLockStatement() { var test = UsingTree(@" class C { void Goo() { [A]lock (null) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LockStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.LockKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NullLiteralExpression); { N(SyntaxKind.NullKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnIfStatement() { var test = UsingTree(@" class C { void Goo() { [A]if (true) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnSwitchStatement() { var test = UsingTree(@" class C { void Goo() { [A]switch (0) { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]switch (0) { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,23): warning CS1522: Empty switch block // [A]switch (0) { } Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(6, 23)); } [Fact] public void AttributeOnStatementInSwitchSection() { var test = UsingTree(@" class C { void Goo() { switch (0) { default: [A]return; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchSection); { N(SyntaxKind.DefaultSwitchLabel); { N(SyntaxKind.DefaultKeyword); N(SyntaxKind.ColonToken); } N(SyntaxKind.ReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (9,17): error CS7014: Attributes are not valid in this context. // [A]return; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(9, 17)); } [Fact] public void AttributeOnStatementAboveCase() { var test = UsingTree(@" class C { void Goo() { switch (0) { [A] case 0: return; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (7,9): warning CS1522: Empty switch block // { Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9), // (7,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10), // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13), // (8,16): error CS1525: Invalid expression term 'case' // [A] Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("case").WithLocation(8, 16), // (8,16): error CS1002: ; expected // [A] Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 16), // (8,16): error CS1513: } expected // [A] Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(8, 16), // (9,19): error CS1002: ; expected // case 0: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 19), // (9,19): error CS1513: } expected // case 0: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 19), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1)); } [Fact] public void AttributeOnStatementAboveDefaultCase() { var test = UsingTree(@" class C { void Goo() { switch (0) { [A] default: return; } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SwitchStatement); { N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DefaultLiteralExpression); { N(SyntaxKind.DefaultKeyword); } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (7,9): warning CS1522: Empty switch block // { Diagnostic(ErrorCode.WRN_EmptySwitch, "{").WithLocation(7, 9), // (7,10): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(7, 10), // (8,13): error CS7014: Attributes are not valid in this context. // [A] Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 13), // (9,13): error CS8716: There is no target type for the default literal. // default: Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 13), // (9,20): error CS1002: ; expected // default: Diagnostic(ErrorCode.ERR_SemicolonExpected, ":").WithLocation(9, 20), // (9,20): error CS1513: } expected // default: Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(9, 20), // (13,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(13, 1)); } [Fact] public void AttributeOnTryStatement() { var test = UsingTree(@" class C { void Goo() { [A]try { } finally { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]try { } finally { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnTryBlock() { var test = UsingTree(@" class C { void Goo() { try [A] { } finally { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,13): error CS7014: Attributes are not valid in this context. // try [A] { } finally { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 13)); } [Fact] public void AttributeOnFinally() { var test = UsingTree(@" class C { void Goo() { try { } [A] finally { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } M(SyntaxKind.FinallyClause); { M(SyntaxKind.FinallyKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.TryStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } M(SyntaxKind.TryKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,15): error CS1524: Expected catch or finally // try { } [A] finally { } Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15), // (6,17): error CS7014: Attributes are not valid in this context. // try { } [A] finally { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17), // (6,21): error CS1003: Syntax error, 'try' expected // try { } [A] finally { } Diagnostic(ErrorCode.ERR_SyntaxError, "finally").WithArguments("try", "finally").WithLocation(6, 21), // (6,21): error CS1514: { expected // try { } [A] finally { } Diagnostic(ErrorCode.ERR_LbraceExpected, "finally").WithLocation(6, 21), // (6,21): error CS1513: } expected // try { } [A] finally { } Diagnostic(ErrorCode.ERR_RbraceExpected, "finally").WithLocation(6, 21)); } [Fact] public void AttributeOnFinallyBlock() { var test = UsingTree(@" class C { void Goo() { try { } finally [A] { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.FinallyClause); { N(SyntaxKind.FinallyKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,25): error CS7014: Attributes are not valid in this context. // try { } finally [A] { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 25)); } [Fact] public void AttributeOnCatch() { var test = UsingTree(@" class C { void Goo() { try { } [A] catch { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } M(SyntaxKind.FinallyClause); { M(SyntaxKind.FinallyKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.TryStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } M(SyntaxKind.TryKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CatchClause); { N(SyntaxKind.CatchKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,15): error CS1524: Expected catch or finally // try { } [A] catch { } Diagnostic(ErrorCode.ERR_ExpectedEndTry, "}").WithLocation(6, 15), // (6,17): error CS7014: Attributes are not valid in this context. // try { } [A] catch { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 17), // (6,21): error CS1003: Syntax error, 'try' expected // try { } [A] catch { } Diagnostic(ErrorCode.ERR_SyntaxError, "catch").WithArguments("try", "catch").WithLocation(6, 21), // (6,21): error CS1514: { expected // try { } [A] catch { } Diagnostic(ErrorCode.ERR_LbraceExpected, "catch").WithLocation(6, 21), // (6,21): error CS1513: } expected // try { } [A] catch { } Diagnostic(ErrorCode.ERR_RbraceExpected, "catch").WithLocation(6, 21)); } [Fact] public void AttributeOnCatchBlock() { var test = UsingTree(@" class C { void Goo() { try { } catch [A] { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.TryStatement); { N(SyntaxKind.TryKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.CatchClause); { N(SyntaxKind.CatchKeyword); N(SyntaxKind.Block); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,23): error CS7014: Attributes are not valid in this context. // try { } catch [A] { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 23)); } [Fact] public void AttributeOnEmbeddedStatement() { var test = UsingTree(@" class C { void Goo() { if (true) [A]return; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IfStatement); { N(SyntaxKind.IfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.TrueLiteralExpression); { N(SyntaxKind.TrueKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SemicolonToken); } } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,19): error CS7014: Attributes are not valid in this context. // if (true) [A]return; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 19)); } [Fact] public void AttributeOnExpressionStatement_AnonymousMethod_NoParameters() { var test = UsingTree(@" class C { void Goo() { [A]delegate { } } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]delegate { } Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,24): error CS1002: ; expected // [A]delegate { } Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 24)); } [Fact] public void AttributeOnExpressionStatement_AnonymousMethod_NoBody() { var test = UsingTree(@" class C { void Goo() { [A]delegate } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); M(SyntaxKind.Block); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]delegate Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,20): error CS1514: { expected // [A]delegate Diagnostic(ErrorCode.ERR_LbraceExpected, "").WithLocation(6, 20), // (6,20): error CS1002: ; expected // [A]delegate Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 20)); } [Fact] public void AttributeOnExpressionStatement_AnonymousMethod_Parameters() { var test = UsingTree(@" class C { void Goo() { [A]delegate () { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousMethodExpression); { N(SyntaxKind.DelegateKeyword); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]delegate () { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]delegate () { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "delegate () { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Lambda_NoParameters() { var test = UsingTree(@" class C { void Goo() { [A]() => { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]() => { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]() => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "() => { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Lambda_Parameters1() { var test = UsingTree(@" class C { void Goo() { [A](int i) => { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ParenthesizedLambdaExpression); { N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A](int i) => { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A](int i) => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "(int i) => { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Lambda_Parameters2() { var test = UsingTree(@" class C { void Goo() { [A]i => { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SimpleLambdaExpression); { N(SyntaxKind.Parameter); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]i => { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]i => { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "i => { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_AnonymousObject() { var test = UsingTree(@" class C { void Goo() { [A]new { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AnonymousObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]new { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "new { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ArrayCreation() { var test = UsingTree(@" class C { void Goo() { [A]new int[] { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.ArrayType); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArrayRankSpecifier); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.OmittedArraySizeExpression); { N(SyntaxKind.OmittedArraySizeExpressionToken); } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new int[] { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]new int[] { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "new int[] { }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_AnonymousArrayCreation() { var test = UsingTree(@" class C { void Goo() { [A]new [] { 0 }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ImplicitArrayCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.OpenBracketToken); N(SyntaxKind.CloseBracketToken); N(SyntaxKind.ArrayInitializerExpression); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new [] { 0 }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]new [] { 0 }; Diagnostic(ErrorCode.ERR_IllegalStatement, "new [] { 0 }").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Assignment() { var test = UsingTree(@" class C { void Goo(int a) { [A]a = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SimpleAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_CompoundAssignment() { var test = UsingTree(@" class C { void Goo(int a) { [A]a += 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AddAssignmentExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusEqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a += 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_AwaitExpression_NonAsyncContext() { var test = UsingTree(@" class C { void Goo() { [A]await a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "await"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0246: The type or namespace name 'await' could not be found (are you missing a using directive or an assembly reference?) // [A]await a; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "await").WithArguments("await").WithLocation(6, 12), // (6,18): warning CS0168: The variable 'a' is declared but never used // [A]await a; Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a").WithLocation(6, 18)); } [Fact] public void AttributeOnExpressionStatement_AwaitExpression_AsyncContext() { var test = UsingTree(@" class C { async void Goo() { [A]await a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitExpression); { N(SyntaxKind.AwaitKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]await a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,18): error CS0103: The name 'a' does not exist in the current context // [A]await a; Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 18)); } [Fact] public void AttributeOnExpressionStatement_BinaryExpression() { var test = UsingTree(@" class C { void Goo(int a) { [A]a + a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AddExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.PlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a + a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a + a; Diagnostic(ErrorCode.ERR_IllegalStatement, "a + a").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_CastExpression() { var test = UsingTree(@" class C { void Goo(int a) { [A](object)a; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.CastExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.ObjectKeyword); } N(SyntaxKind.CloseParenToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A](object)a; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A](object)a; Diagnostic(ErrorCode.ERR_IllegalStatement, "(object)a").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ConditionalAccess() { var test = UsingTree(@" class C { void Goo(string a) { [A]a?.ToString(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.MemberBindingExpression); { N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ToString"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a?.ToString(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_DefaultExpression() { var test = UsingTree(@" class C { void Goo() { [A]default(int); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DefaultExpression); { N(SyntaxKind.DefaultKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]default(int); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]default(int); Diagnostic(ErrorCode.ERR_IllegalStatement, "default(int)").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_DefaultLiteral() { var test = UsingTree(@" class C { void Goo() { [A]default; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.DefaultLiteralExpression); { N(SyntaxKind.DefaultKeyword); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]default; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS8716: There is no target type for the default literal. // [A]default; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]default; Diagnostic(ErrorCode.ERR_IllegalStatement, "default").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ElementAccess() { var test = UsingTree(@" class C { void Goo(string s) { [A]s[0]; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]s[0]; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]s[0]; Diagnostic(ErrorCode.ERR_IllegalStatement, "s[0]").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ElementBinding() { var test = UsingTree(@" class C { void Goo(string s) { [A]s?[0]; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ConditionalAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.QuestionToken); N(SyntaxKind.ElementBindingExpression); { N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } N(SyntaxKind.CloseBracketToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]s?[0]; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]s?[0]; Diagnostic(ErrorCode.ERR_IllegalStatement, "s?[0]").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Invocation() { var test = UsingTree(@" class C { void Goo() { [A]Goo(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Goo"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]Goo(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_Literal() { var test = UsingTree(@" class C { void Goo() { [A]0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]0; Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_MemberAccess() { var test = UsingTree(@" class C { void Goo(int i) { [A]i.ToString; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "ToString"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]i.ToString; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]i.ToString; Diagnostic(ErrorCode.ERR_IllegalStatement, "i.ToString").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_ObjectCreation_Builtin() { var test = UsingTree(@" class C { void Goo() { [A]new int(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new int(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_ObjectCreation_TypeName() { var test = UsingTree(@" class C { void Goo() { [A]new System.Int32(); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ObjectCreationExpression); { N(SyntaxKind.NewKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Int32"); } } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]new System.Int32(); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_Parenthesized() { var test = UsingTree(@" class C { void Goo() { [A](1); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ParenthesizedExpression); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A](1); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A](1); Diagnostic(ErrorCode.ERR_IllegalStatement, "(1)").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_PostfixUnary() { var test = UsingTree(@" class C { void Goo(int i) { [A]i++; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PostIncrementExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.PlusPlusToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]i++; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_PrefixUnary() { var test = UsingTree(@" class C { void Goo(int i) { [A]++i; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PreIncrementExpression); { N(SyntaxKind.PlusPlusToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]++i; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnExpressionStatement_Query() { var test = UsingTree(@" using System.Linq; class C { void Goo(string s) { [A]from c in s select c; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.UsingDirective); { N(SyntaxKind.UsingKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Linq"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.StringKeyword); } N(SyntaxKind.IdentifierToken, "s"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.QueryExpression); { N(SyntaxKind.FromClause); { N(SyntaxKind.FromKeyword); N(SyntaxKind.IdentifierToken, "c"); N(SyntaxKind.InKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "s"); } } N(SyntaxKind.QueryBody); { N(SyntaxKind.SelectClause); { N(SyntaxKind.SelectKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "c"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (7,9): error CS7014: Attributes are not valid in this context. // [A]from c in s select c; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(7, 9), // (7,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]from c in s select c; Diagnostic(ErrorCode.ERR_IllegalStatement, "from c in s select c").WithLocation(7, 12)); } [Fact] public void AttributeOnExpressionStatement_Range1() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]a..b; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotDotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a..b; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]a..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..b").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]a..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a..b; Diagnostic(ErrorCode.ERR_IllegalStatement, "a..b").WithLocation(6, 12), // (6,15): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]a..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 15)); } [Fact] public void AttributeOnExpressionStatement_Range2() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]a..; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotDotToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a..; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]a..; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a..").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]a..; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "a").WithArguments("System.Index").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a..; Diagnostic(ErrorCode.ERR_IllegalStatement, "a..").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Range3() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]..b; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.DotDotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]..b; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..b").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]..b; Diagnostic(ErrorCode.ERR_IllegalStatement, "..b").WithLocation(6, 12), // (6,14): error CS0518: Predefined type 'System.Index' is not defined or imported // [A]..b; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "b").WithArguments("System.Index").WithLocation(6, 14)); } [Fact] public void AttributeOnExpressionStatement_Range4() { var test = UsingTree(@" class C { void Goo(int a, int b) { [A]..; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CommaToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "b"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.RangeExpression); { N(SyntaxKind.DotDotToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]..; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.Range' is not defined or imported // [A]..; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "..").WithArguments("System.Range").WithLocation(6, 12), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]..; Diagnostic(ErrorCode.ERR_IllegalStatement, "..").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_Sizeof() { var test = UsingTree(@" class C { void Goo() { [A]sizeof(int); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SizeOfExpression); { N(SyntaxKind.SizeOfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]sizeof(int); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]sizeof(int); Diagnostic(ErrorCode.ERR_IllegalStatement, "sizeof(int)").WithLocation(6, 12)); } [Fact] public void AttributeOnExpressionStatement_SwitchExpression() { var test = UsingTree(@" class C { void Goo(int a) { [A]a switch { }; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.SwitchExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.SwitchKeyword); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]a switch { }; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]a switch { }; Diagnostic(ErrorCode.ERR_IllegalStatement, "a switch { }").WithLocation(6, 12), // (6,14): 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. // [A]a switch { }; Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(6, 14), // (6,14): error CS8506: No best type was found for the switch expression. // [A]a switch { }; Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(6, 14)); } [Fact] public void AttributeOnExpressionStatement_TypeOf() { var test = UsingTree(@" class C { void Goo() { [A]typeof(int); } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.TypeOfExpression); { N(SyntaxKind.TypeOfKeyword); N(SyntaxKind.OpenParenToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]typeof(int); Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]typeof(int); Diagnostic(ErrorCode.ERR_IllegalStatement, "typeof(int)").WithLocation(6, 12)); } [Fact] public void AttributeOnLocalDeclOrMember1() { var test = UsingTree(@" class C { void Goo() { [A]int i; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int i; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): warning CS0168: The variable 'i' is declared but never used // [A]int i; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16)); } [Fact] public void AttributeOnLocalDeclOrMember2() { var test = UsingTree(@" class C { void Goo() { [A]int i, j; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); } N(SyntaxKind.CommaToken); N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "j"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int i, j; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): warning CS0168: The variable 'i' is declared but never used // [A]int i, j; Diagnostic(ErrorCode.WRN_UnreferencedVar, "i").WithArguments("i").WithLocation(6, 16), // (6,19): warning CS0168: The variable 'j' is declared but never used // [A]int i, j; Diagnostic(ErrorCode.WRN_UnreferencedVar, "j").WithArguments("j").WithLocation(6, 19)); } [Fact] public void AttributeOnLocalDeclOrMember3() { var test = UsingTree(@" class C { void Goo() { [A]int i = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): warning CS0219: The variable 'i' is assigned but its value is never used // [A]int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 16)); } [Fact] public void AttributeOnLocalDeclOrMember4() { var test = UsingTree(@" class C { void Goo() { [A]int this[int i] => 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.VariableDeclarator); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.ElementAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.BracketedArgumentList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Argument); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } } M(SyntaxKind.CommaToken); N(SyntaxKind.Argument); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "i"); } } N(SyntaxKind.CloseBracketToken); } } M(SyntaxKind.SemicolonToken); } N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,16): error CS1001: Identifier expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_IdentifierExpected, "this").WithLocation(6, 16), // (6,16): error CS1002: ; expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_SemicolonExpected, "this").WithLocation(6, 16), // (6,21): error CS1525: Invalid expression term 'int' // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 21), // (6,25): error CS1003: Syntax error, ',' expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_SyntaxError, "i").WithArguments(",", "").WithLocation(6, 25), // (6,25): error CS0103: The name 'i' does not exist in the current context // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_NameNotInContext, "i").WithArguments("i").WithLocation(6, 25), // (6,28): error CS1002: ; expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_SemicolonExpected, "=>").WithLocation(6, 28), // (6,28): error CS1513: } expected // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_RbraceExpected, "=>").WithLocation(6, 28), // (6,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // [A]int this[int i] => 0; Diagnostic(ErrorCode.ERR_IllegalStatement, "0").WithLocation(6, 31)); } [Fact] public void AttributeOnLocalDeclOrMember5() { var tree = UsingTree(@" class C { void Goo() { [A]const int i = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.ConstKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(tree).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]const int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,22): warning CS0219: The variable 'i' is assigned but its value is never used // [A]const int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 22)); } [Fact] public void AccessModOnLocalDeclOrMember_01() { var test = UsingTree(@" class C { void Goo() { public extern int i = 1; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.ExternKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).VerifyDiagnostics( // (5,6): error CS1513: } expected // { Diagnostic(ErrorCode.ERR_RbraceExpected, "").WithLocation(5, 6), // (6,27): error CS0106: The modifier 'extern' is not valid for this item // public extern int i = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "i").WithArguments("extern").WithLocation(6, 27), // (8,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(8, 1)); } [Fact] public void AccessModOnLocalDeclOrMember_02() { var test = UsingTree(@" class C { void Goo() { extern public int i = 1; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.ExternKeyword); N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "1"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).VerifyDiagnostics( // (6,9): error CS0106: The modifier 'extern' is not valid for this item // extern public int i = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "extern").WithArguments("extern").WithLocation(6, 9), // (6,16): error CS0106: The modifier 'public' is not valid for this item // extern public int i = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 16), // (6,27): warning CS0219: The variable 'i' is assigned but its value is never used // extern public int i = 1; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 27)); } [Fact] public void AttributeOnLocalDeclOrMember6() { var test = UsingTree(@" class C { void Goo() { [A]public int i = 0; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.NumericLiteralExpression); { N(SyntaxKind.NumericLiteralToken, "0"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]public int i = 0; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0106: The modifier 'public' is not valid for this item // [A]public int i = 0; Diagnostic(ErrorCode.ERR_BadMemberFlag, "public").WithArguments("public").WithLocation(6, 12), // (6,23): warning CS0219: The variable 'i' is assigned but its value is never used // [A]public int i = 0; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(6, 23)); } [Fact] public void AttributeOnLocalDeclOrMember7() { var test = UsingTree(@" class C { void Goo(System.IDisposable d) { [A]using var i = d; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IDisposable"); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (6,9): error CS7014: Attributes are not valid in this context. // [A]using var i = d; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9)); } [Fact] public void AttributeOnLocalDeclOrMember8() { var test = UsingTree(@" class C { void Goo(System.IAsyncDisposable d) { [A]await using var i = d; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IAsyncDisposable"); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,21): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?) // void Goo(System.IAsyncDisposable d) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 21), // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using var i = d; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using var i = d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12), // (6,12): 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'. // [A]await using var i = d; Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await").WithLocation(6, 12)); } [Fact] public void AttributeOnLocalDeclOrMember9() { var test = UsingTree(@" class C { async void Goo(System.IAsyncDisposable d) { [A]await using var i = d; } }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.AsyncKeyword); N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Parameter); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "IAsyncDisposable"); } } N(SyntaxKind.IdentifierToken, "d"); } N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.LocalDeclarationStatement); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "A"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.AwaitKeyword); N(SyntaxKind.UsingKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "i"); N(SyntaxKind.EqualsValueClause); { N(SyntaxKind.EqualsToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "d"); } } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); CreateCompilation(test).GetDiagnostics().Verify( // (4,27): error CS0234: The type or namespace name 'IAsyncDisposable' does not exist in the namespace 'System' (are you missing an assembly reference?) // async void Goo(System.IAsyncDisposable d) Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "IAsyncDisposable").WithArguments("IAsyncDisposable", "System").WithLocation(4, 27), // (6,9): error CS7014: Attributes are not valid in this context. // [A]await using var i = d; Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(6, 9), // (6,12): error CS0518: Predefined type 'System.IAsyncDisposable' is not defined or imported // [A]await using var i = d; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "await").WithArguments("System.IAsyncDisposable").WithLocation(6, 12)); } [Fact] public void AttrDeclOnStatementWhereMemberExpected() { UsingTree(@" class C { [Attr] x.y(); } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.IncompleteMember); { N(SyntaxKind.AttributeList); { N(SyntaxKind.OpenBracketToken); N(SyntaxKind.Attribute); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Attr"); } } N(SyntaxKind.CloseBracketToken); } N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "x"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "y"); } } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.TupleType); { N(SyntaxKind.OpenParenToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.CommaToken); M(SyntaxKind.TupleElement); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Xaml/Impl/Diagnostics/XamlDiagnosticIds.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.Xaml.Diagnostics { internal static class XamlDiagnosticIds { public const string UnnecessaryNamespacesId = "XAML1103"; public const string MissingNamespaceId = "XAML0002"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Xaml.Diagnostics { internal static class XamlDiagnosticIds { public const string UnnecessaryNamespacesId = "XAML1103"; public const string MissingNamespaceId = "XAML0002"; } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Test/Symbol/Symbols/SymbolErrorTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; 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 partial class CompilationErrorTests : CompilingTestBase { #region Symbol Error Tests private static readonly ModuleMetadata s_mod1 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod01); private static readonly ModuleMetadata s_mod2 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod02); [Fact()] public void CS0148ERR_BadDelegateConstructor() { var il = @" .class public auto ansi sealed F extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor( //object 'object', native int 'method') runtime managed { } // end of method F::.ctor .method public hidebysig newslot virtual instance void Invoke() runtime managed { } // end of method F::Invoke .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } // end of method F::BeginInvoke .method public hidebysig newslot virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed { } // end of method F::EndInvoke } // end of class F "; var source = @" class C { void Goo() { F del = Goo; del(); //need to use del or the delegate receiver alone is emitted in optimized code. } } "; var comp = CreateCompilationWithILAndMscorlib40(source, il); var emitResult = comp.Emit(new System.IO.MemoryStream()); emitResult.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_BadDelegateConstructor, "Goo").WithArguments("F")); } /// <summary> /// This error is specific to netmodule scenarios /// We used to give error CS0011: The base class or interface 'A' in assembly 'xxx' referenced by type 'B' could not be resolved /// In Roslyn we do not know the context in which the lookup was occurring, so we give a new, more generic message. /// </summary> [WorkItem(546451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546451")] [Fact()] public void CS0011ERR_CantImportBase01() { var text1 = @"class A {}"; var text2 = @"class B : A {}"; var text = @" class Test { B b; void M() { Test x = b; } }"; var name1 = GetUniqueName(); var module1 = CreateCompilation(text1, options: TestOptions.ReleaseModule, assemblyName: name1); var module2 = CreateCompilation(text2, options: TestOptions.ReleaseModule, references: new[] { ModuleMetadata.CreateFromImage(module1.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); // use ref2 only var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_UnreferencedField), ReportDiagnostic.Suppress } }), references: new[] { ModuleMetadata.CreateFromImage(module2.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); comp.VerifyDiagnostics( // error CS8014: Reference to '1b2d660e-e892-4338-a4e7-f78ce7960ce9.netmodule' netmodule missing. Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments(name1 + ".netmodule"), // (8,18): error CS7079: The type 'A' is defined in a module that has not been added. You must add the module '2bddf16b-09e6-4c4d-bd08-f348e194eca4.netmodule'. // Test x = b; Diagnostic(ErrorCode.ERR_NoTypeDefFromModule, "b").WithArguments("A", name1 + ".netmodule"), // (8,18): error CS0029: Cannot implicitly convert type 'B' to 'Test' // Test x = b; Diagnostic(ErrorCode.ERR_NoImplicitConv, "b").WithArguments("B", "Test"), // (4,7): warning CS0649: Field 'Test.b' is never assigned to, and will always have its default value null // B b; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "b").WithArguments("Test.b", "null") ); } [Fact] public void CS0012ERR_NoTypeDef01() { var text = @"namespace NS { class Test { TC5<string, string> var; // inherit C1 from MDTestLib1.dll void M() { Test x = var; } } }"; var ref2 = TestReferences.SymbolsTests.MDTestLib2; var comp = CreateCompilation(text, references: new MetadataReference[] { ref2 }, assemblyName: "Test3"); comp.VerifyDiagnostics( // (9,22): error CS0012: The type 'C1<>.C2<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Test x = var; Diagnostic(ErrorCode.ERR_NoTypeDef, "var").WithArguments("C1<>.C2<>", "MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,22): error CS0029: Cannot implicitly convert type 'TC5<string, string>' to 'NS.Test' // Test x = var; Diagnostic(ErrorCode.ERR_NoImplicitConv, "var").WithArguments("TC5<string, string>", "NS.Test"), // (5,28): warning CS0649: Field 'NS.Test.var' is never assigned to, and will always have its default value null // TC5<string, string> var; // inherit C1 from MDTestLib1.dll Diagnostic(ErrorCode.WRN_UnassignedInternalField, "var").WithArguments("NS.Test.var", "null") ); } [Fact, WorkItem(8574, "DevDiv_Projects/Roslyn")] public void CS0029ERR_CannotImplicitlyConvertTypedReferenceToObject() { var text = @" class Program { static void M(System.TypedReference r) { var t = r.GetType(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // var t = r.GetType(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "r").WithArguments("System.TypedReference", "object")); } // CS0036: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0050ERR_BadVisReturnType() { var text = @"class MyClass { } public class MyClass2 { public static MyClass MyMethod() // CS0050 { return new MyClass(); } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisReturnType, Line = 7, Column = 27 }); } [Fact] public void CS0051ERR_BadVisParamType01() { var text = @"public class A { class B { } public static void F(B b) // CS0051 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType02() { var text = @"class A { protected class P1 { } public class N { public void f(P1 p) { } protected void g(P1 p) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 8, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType03() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 { public void M(B<A> arg) { } } public class C2 { public void M(B<object>.C<A> arg) { } } public class C3 { public void M(B<A>.C<object> arg) { } } public class C4 { public void M(B<B<A>>.C<object> arg) { } }"; CreateCompilation(source).VerifyDiagnostics( // (8,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>' is less accessible than method 'C1.M(B<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C1.M(B<A>)", "B<A>").WithLocation(8, 17), // (12,17): error CS0051: Inconsistent accessibility: parameter type 'B<object>.C<A>' is less accessible than method 'C2.M(B<object>.C<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C2.M(B<object>.C<A>)", "B<object>.C<A>").WithLocation(12, 17), // (16,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>.C<object>' is less accessible than method 'C3.M(B<A>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C3.M(B<A>.C<object>)", "B<A>.C<object>").WithLocation(16, 17), // (20,17): error CS0051: Inconsistent accessibility: parameter type 'B<B<A>>.C<object>' is less accessible than method 'C4.M(B<B<A>>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C4.M(B<B<A>>.C<object>)", "B<B<A>>.C<object>").WithLocation(20, 17)); } [Fact] public void CS0052ERR_BadVisFieldType() { var text = @"public class MyClass2 { public MyClass M; // CS0052 private class MyClass { } } public class MainClass { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisFieldType, Line = 3, Column = 20 }); } [Fact] public void CS0053ERR_BadVisPropertyType() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class B { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class D { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.Q", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("A.R", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.S", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("A.V", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.W", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.B.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.B.Q", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.B.S", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.B.W", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("C.R", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.S", "C.PrivateClass").WithLocation(34, 25), // (370): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("C.V", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.W", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.D.S", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.D.W", "C.PrivateClass").WithLocation(48, 31)); } [ClrOnlyFact] public void CS0054ERR_BadVisIndexerReturn() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class B { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class D { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[object]", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string]", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double]", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string, string]", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double, double]", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.B.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[object]", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double]", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double, double]", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string]", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double]", "C.PrivateClass").WithLocation(34, 25), // (370): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string, string]", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double, double]", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double]", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double, double]", "C.PrivateClass").WithLocation(48, 31)); } [Fact] public void CS0055ERR_BadVisIndexerParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public int this[MyClass myClass] // CS0055 { get { return 0; } } } public class MyClass3 { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisIndexerParam, Line = 7, Column = 16 }); } [Fact] public void CS0056ERR_BadVisOpReturn() { var text = @"class MyClass { } public class A { public static implicit operator MyClass(A a) // CS0056 { return new MyClass(); } public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,28): error CS0056: Inconsistent accessibility: return type 'MyClass' is less accessible than operator 'A.implicit operator MyClass(A)' // public static implicit operator MyClass(A a) // CS0056 Diagnostic(ErrorCode.ERR_BadVisOpReturn, "MyClass").WithArguments("A.implicit operator MyClass(A)", "MyClass") ); } [Fact] public void CS0057ERR_BadVisOpParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public static implicit operator MyClass2(MyClass iii) // CS0057 { return new MyClass2(); } public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (77): error CS0057: Inconsistent accessibility: parameter type 'MyClass' is less accessible than operator 'MyClass2.implicit operator MyClass2(MyClass)' // public static implicit operator MyClass2(MyClass iii) // CS0057 Diagnostic(ErrorCode.ERR_BadVisOpParam, "MyClass2").WithArguments("MyClass2.implicit operator MyClass2(MyClass)", "MyClass")); } [Fact] public void CS0058ERR_BadVisDelegateReturn() { var text = @"class MyClass { } public delegate MyClass MyClassDel(); // CS0058 public class A { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisDelegateReturn, Line = 5, Column = 25 }); } [WorkItem(542005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542005")] [Fact] public void CS0058ERR_BadVisDelegateReturn02() { var text = @" public class Outer { protected class Test { } public delegate Test MyDelegate(); }"; CreateCompilation(text).VerifyDiagnostics( // (5,26): error CS0058: Inconsistent accessibility: return type 'Outer.Test' is less accessible than delegate 'Outer.MyDelegate' // public delegate Test MyDelegate(); Diagnostic(ErrorCode.ERR_BadVisDelegateReturn, "MyDelegate").WithArguments("Outer.MyDelegate", "Outer.Test").WithLocation(5, 26) ); } [Fact] public void CS0059ERR_BadVisDelegateParam() { var text = @" class MyClass {} //defaults to internal accessibility public delegate void MyClassDel(MyClass myClass); // CS0059 "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,22): error CS0059: Inconsistent accessibility: parameter type 'MyClass' is less accessible than delegate 'MyClassDel' // public delegate void MyClassDel(MyClass myClass); // CS0059 Diagnostic(ErrorCode.ERR_BadVisDelegateParam, "MyClassDel").WithArguments("MyClassDel", "MyClass") ); } [Fact] public void CS0060ERR_BadVisBaseClass() { var text = @" namespace NS { internal class MyBase { } public class MyClass : MyBase { } public class Outer { private class MyBase { } protected class MyClass : MyBase { } protected class MyBase01 { } protected internal class MyClass01 : MyBase { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 34 }); } [WorkItem(539511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539511")] [Fact] public void CS0060ERR_BadVisBaseClass02() { var text = @" public class A<T> { public class B<S> : A<B<D>.C> { public class C { } } protected class D { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 18 }); } [WorkItem(539512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539512")] [Fact] public void CS0060ERR_BadVisBaseClass03() { var text = @" public class A { protected class B { protected class C { } } } internal class F : A { private class D : B { public class E : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 22 }); } [WorkItem(539546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539546")] [Fact] public void CS0060ERR_BadVisBaseClass04() { var text = @" public class A<T> { private class B : A<B.C> { private class C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 19 }); } [WorkItem(539562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539562")] [Fact] public void CS0060ERR_BadVisBaseClass05() { var text = @" class A<T> { class B : A<B> { public class C : B { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(539950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539950")] [Fact] public void CS0060ERR_BadVisBaseClass06() { var text = @" class A : C<E.F> { public class B { public class D { protected class F { } } } } class C<T> { } class E : A.B.D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // E.F is inaccessible where written; cascaded ERR_BadVisBaseClass is therefore suppressed new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 2, Column = 15 }); } [Fact] public void CS0060ERR_BadVisBaseClass07() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 : B<A> { } public class C2 : B<object>.C<A> { } public class C3 : B<A>.C<object> { } public class C4 : B<B<A>>.C<object> { }"; CreateCompilation(source).VerifyDiagnostics( // (6,14): error CS0060: Inconsistent accessibility: base type 'B<A>' is less accessible than class 'C1' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "B<A>").WithLocation(6, 14), // (7,14): error CS0060: Inconsistent accessibility: base type 'B<object>.C<A>' is less accessible than class 'C2' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C2").WithArguments("C2", "B<object>.C<A>").WithLocation(7, 14), // (8,14): error CS0060: Inconsistent accessibility: base type 'B<A>.C<object>' is less accessible than class 'C3' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C3").WithArguments("C3", "B<A>.C<object>").WithLocation(8, 14), // (9,14): error CS0060: Inconsistent accessibility: base type 'B<B<A>>.C<object>' is less accessible than class 'C4' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C4").WithArguments("C4", "B<B<A>>.C<object>").WithLocation(9, 14)); } [Fact] public void CS0060ERR_BadVisBaseClass08() { var source = @"public class A { internal class B { public interface C { } } } public class B<T> : A { } public class C : B<A.B.C> { }"; CreateCompilation(source).VerifyDiagnostics( // (9,14): error CS0060: Inconsistent accessibility: base type 'B<A.B.C>' is less accessible than class 'C' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("C", "B<A.B.C>").WithLocation(9, 14)); } [Fact] public void CS0061ERR_BadVisBaseInterface() { var text = @"internal interface A { } public interface AA : A { } // CS0061 // OK public interface B { } internal interface BB : B { } internal interface C { } internal interface CC : C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseInterface, Line = 2, Column = 18 }); } [Fact] public void CS0065ERR_EventNeedsBothAccessors() { var text = @"using System; public delegate void Eventhandler(object sender, int e); public class MyClass { public event EventHandler E1 { } // CS0065, public event EventHandler E2 { add { } } // CS0065, public event EventHandler E3 { remove { } } // CS0065, } "; CreateCompilation(text).VerifyDiagnostics( // (5,31): error CS0065: 'MyClass.E1': event property must have both add and remove accessors // public event EventHandler E1 { } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("MyClass.E1"), // (6,31): error CS0065: 'MyClass.E2': event property must have both add and remove accessors // public event EventHandler E2 { add { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("MyClass.E2"), // (71): error CS0065: 'MyClass.E3': event property must have both add and remove accessors // public event EventHandler E3 { remove { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E3").WithArguments("MyClass.E3")); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface01() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,22): error CS0065: 'i1.myevent': event property must have both add and remove accessors Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "myevent").WithArguments("i1.myevent")); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface02() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add; remove; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (6,35): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 35), // (6,43): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 43)); CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (6,35): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 35), // (6,43): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 43), // (6,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 32), // (6,37): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 37) ); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface03() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} remove {} } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (5,39): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(5, 39) ); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface04() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (5,22): error CS0065: 'i1.myevent': event property must have both add and remove accessors // event myDelegate myevent { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "myevent").WithArguments("i1.myevent").WithLocation(5, 22) ); } [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface05() { var text = @" public interface I2 { } public interface I1 { event System.Action I2.P10; } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P10").WithLocation(6, 28), // (6,25): error CS0540: 'I1.P10': containing type does not implement interface 'I2' // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P10", "I2").WithLocation(6, 25), // (6,28): error CS0539: 'I1.P10' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P10").WithArguments("I1.P10").WithLocation(6, 28) ); } [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface06() { var text = @" public interface I2 { } public interface I1 { event System.Action I2. P10; } "; CreateCompilation(text).VerifyDiagnostics( // (6,25): error CS0540: 'I1.P10': containing type does not implement interface 'I2' // event System.Action I2. Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P10", "I2").WithLocation(6, 25), // (7,1): error CS0071: An explicit interface implementation of an event must use event accessor syntax // P10; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P10").WithLocation(7, 1), // (7,1): error CS0539: 'I1.P10' in explicit interface declaration is not found among members of the interface that can be implemented // P10; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P10").WithArguments("I1.P10").WithLocation(7, 1) ); } [Fact] public void CS0066ERR_EventNotDelegate() { var text = @" public class C { public event C Click; // CS0066 } "; CreateCompilation(text).VerifyDiagnostics( // (4,20): error CS0066: 'C.Click': event must be of a delegate type // public event C Click; // CS0066 Diagnostic(ErrorCode.ERR_EventNotDelegate, "Click").WithArguments("C.Click"), // (4,20): warning CS0067: The event 'C.Click' is never used // public event C Click; // CS0066 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("C.Click")); } [Fact] public void CS0068ERR_InterfaceEventInitializer() { var text = @" delegate void MyDelegate(); interface I { event MyDelegate d = new MyDelegate(M.f); // CS0068 } class M { event MyDelegate d = new MyDelegate(M.f); public static void f() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0068: 'I.d': event in interface cannot have initializer // event MyDelegate d = new MyDelegate(M.f); // CS0068 Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "d").WithArguments("I.d").WithLocation(6, 22), // (6,22): warning CS0067: The event 'I.d' is never used // event MyDelegate d = new MyDelegate(M.f); // CS0068 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "d").WithArguments("I.d").WithLocation(6, 22)); } [Fact] public void CS0072ERR_CantOverrideNonEvent() { var text = @"delegate void MyDelegate(); class Test1 { public virtual event MyDelegate MyEvent; public virtual void VMeth() { } } class Test2 : Test1 { public override event MyDelegate VMeth // CS0072 { add { VMeth += value; } remove { VMeth -= value; } } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (13,38): error CS0072: 'Test2.VMeth': cannot override; 'Test1.VMeth()' is not an event // public override event MyDelegate VMeth // CS0072 Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "VMeth").WithArguments("Test2.VMeth", "Test1.VMeth()"), // (5,37): warning CS0067: The event 'Test1.MyEvent' is never used // public virtual event MyDelegate MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test1.MyEvent")); } [Fact] public void CS0074ERR_AbstractEventInitializer() { var text = @" delegate void D(); abstract class Test { public abstract event D e = null; // CS0074 } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0074: 'Test.e': abstract event cannot have initializer // public abstract event D e = null; // CS0074 Diagnostic(ErrorCode.ERR_AbstractEventInitializer, "e").WithArguments("Test.e").WithLocation(6, 29), // (6,29): warning CS0414: The field 'Test.e' is assigned but its value is never used // public abstract event D e = null; // CS0074 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("Test.e").WithLocation(6, 29)); } [Fact] public void CS0076ERR_ReservedEnumerator() { var text = @"enum E { value__ } enum F { A, B, value__ } enum G { X = 0, value__ = 1, Z = value__ + 1 } enum H { Value__ } // no error class C { E value__; // no error static void M() { F value__; // no error } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (1,10): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum E { value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (2,16): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum F { A, B, value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (3,17): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum G { X = 0, value__ = 1, Z = value__ + 1 } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (10,11): warning CS0168: The variable 'value__' is declared but never used // F value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedVar, "value__").WithArguments("value__"), // (7,7): warning CS0169: The field 'C.value__' is never used // E value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "value__").WithArguments("C.value__") ); } /// <summary> /// Currently parser error 1001, 1003. Is that good enough? /// </summary> [Fact()] public void CS0081ERR_TypeParamMustBeIdentifier01() { var text = @"namespace NS { class C { int F<int>() { } // CS0081 } }"; // Triage decision was made to have this be a parse error as the grammar specifies it as such. // TODO: vsadov, the error recovery would be much nicer here if we consumed "int", bu tneed to consider other cases. CreateCompilationWithMscorlib46(text, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (5,11): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '>' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(">", "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '(' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("(", "int").WithLocation(5, 11), // (5,14): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(5, 14), // (5,14): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, ">").WithArguments(",", ">").WithLocation(5, 14), // (5,15): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "(").WithLocation(5, 15), // (5,16): error CS8124: Tuple must contain at least two elements. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 16), // (5,18): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 18), // (5,18): error CS1026: ) expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(5, 18), // (5,15): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 15), // (5,9): error CS0161: 'C.F<>(int, (?, ?))': not all code paths return a value // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("NS.C.F<>(int, (?, ?))").WithLocation(5, 9) ); } /// <summary> /// Currently parser error 1001, 1003. Is that good enough? /// </summary> [Fact()] public void CS0081ERR_TypeParamMustBeIdentifier01WithCSharp6() { var text = @"namespace NS { class C { int F<int>() { } // CS0081 } }"; // Triage decision was made to have this be a parse error as the grammar specifies it as such. CreateCompilationWithMscorlib46(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (5,11): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '>' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(">", "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '(' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("(", "int").WithLocation(5, 11), // (5,14): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(5, 14), // (5,14): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, ">").WithArguments(",", ">").WithLocation(5, 14), // (5,15): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "(").WithLocation(5, 15), // (5,15): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "()").WithArguments("tuples", "7.0").WithLocation(5, 15), // (5,16): error CS8124: Tuple must contain at least two elements. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 16), // (5,18): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 18), // (5,18): error CS1026: ) expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(5, 18), // (5,15): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 15), // (5,9): error CS0161: 'C.F<>(int, (?, ?))': not all code paths return a value // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("NS.C.F<>(int, (?, ?))").WithLocation(5, 9) ); } [Fact] public void CS0082ERR_MemberReserved01() { CreateCompilation( @"class C { public void set_P(int i) { } public int P { get; set; } public int get_P() { return 0; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(4, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(4, 25)); } [Fact] public void CS0082ERR_MemberReserved02() { CreateCompilation( @"class A { public void set_P(int i) { } } partial class B : A { public int P { get { return 0; } set { } } } partial class B { partial void get_P(); public void set_P() { } } partial class B { partial void get_P() { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "B").WithLocation(9, 9)); } [Fact] public void CS0082ERR_MemberReserved03() { CreateCompilation( @"abstract class C { public abstract object P { get; } protected abstract object Q { set; } internal object R { get; set; } protected internal object S { get { return null; } } private object T { set { } } object U { get { return null; } set { } } object get_P() { return null; } void set_P(object value) { } private object get_Q() { return null; } private void set_Q(object value) { } protected internal object get_R() { return null; } protected internal void set_R(object value) { } internal object get_S() { return null; } internal void set_S(object value) { } protected object get_T() { return null; } protected void set_T(object value) { } public object get_U() { return null; } public void set_U(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(3, 32), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C").WithLocation(3, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "Q").WithArguments("get_Q", "C").WithLocation(4, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_R", "C").WithLocation(5, 25), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(5, 30), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_S", "C").WithLocation(6, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "S").WithArguments("set_S", "C").WithLocation(6, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "T").WithArguments("get_T", "C").WithLocation(7, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_T", "C").WithLocation(7, 24), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_U", "C").WithLocation(8, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_U", "C").WithLocation(8, 37)); } [Fact] public void CS0082ERR_MemberReserved04() { CreateCompilationWithMscorlib40AndSystemCore( @"class A<T, U> { public T P { get; set; } // CS0082 public U Q { get; set; } // no error public U R { get; set; } // no error public void set_P(T t) { } public void set_Q(object o) { } public void set_R(T t) { } } class B : A<object, object> { } class C { public dynamic P { get; set; } // CS0082 public dynamic Q { get; set; } // CS0082 public object R { get; set; } // CS0082 public object S { get; set; } // CS0082 public void set_P(object o) { } public void set_Q(dynamic o) { } public void set_R(object o) { } public void set_S(dynamic o) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "A<T, U>").WithLocation(3, 23), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(15, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(16, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(17, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(18, 28)); } [Fact] public void CS0082ERR_MemberReserved05() { CreateCompilation( @"class C { object P { get; set; } object Q { get; set; } object R { get; set; } object[] S { get; set; } public object get_P(object o) { return null; } // CS0082 public void set_P() { } public void set_P(ref object o) { } public void get_Q() { } // CS0082 public object set_Q(object o) { return null; } // CS0082 public object set_Q(out object o) { o = null; return null; } void set_S(params object[] args) { } // CS0082 } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_Q", "C").WithLocation(4, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 21), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(6, 23)); } [Fact] public void CS0082ERR_MemberReserved06() { // No errors for explicit interface implementation. CreateCompilation( @"interface I { int get_P(); void set_P(int o); } class C : I { public int P { get; set; } int I.get_P() { return 0; } void I.set_P(int o) { } } ") .VerifyDiagnostics(); } [WorkItem(539770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539770")] [Fact] public void CS0082ERR_MemberReserved07() { // No errors for explicit interface implementation. CreateCompilation( @"class C { public object P { get { return null; } } object get_P() { return null; } void set_P(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C"), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C")); } [Fact] public void CS0082ERR_MemberReserved08() { CreateCompilation( @"class C { public event System.Action E; void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,32): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("add_E", "C"), // (3,32): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("remove_E", "C"), // (3,32): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0082ERR_MemberReserved09() { CreateCompilation( @"class C { public event System.Action E { add { } remove { } } void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,36): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "add").WithArguments("add_E", "C"), // (3,44): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "remove").WithArguments("remove_E", "C")); } [Fact] public void CS0100ERR_DuplicateParamName01() { var text = @"namespace NS { interface IGoo { void M1(byte b, sbyte b); } struct S { public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (5,31): error CS0100: The parameter name 'b' is a duplicate // void M1(byte b, sbyte b); Diagnostic(ErrorCode.ERR_DuplicateParamName, "b").WithArguments("b").WithLocation(5, 31), // (10,45): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 45), // (10,59): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 59), // (10,77): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 77), // (10,82): error CS0229: Ambiguity between 'object' and 'ref string' // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_AmbigMember, "p").WithArguments("object", "ref string").WithLocation(10, 82) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS01() { var text = @"namespace NS { struct Test { } class Test { } interface Test { } namespace NS1 { interface A<T, V> { } class A<T, V> { } class A<T, V> { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 10, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 11, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS02() { var text = @"namespace NS { interface IGoo<T, V> { } class IGoo<T, V> { } struct SS { } public class SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS03() { var text = @"namespace NS { interface IGoo<T, V> { } interface IGoo<T, V> { } struct SS { } public struct SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS04() { var text = @"namespace NS { partial class Goo<T, V> { } // no error, because ""partial"" partial class Goo<T, V> { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0102ERR_DuplicateNameInClass01() { var text = @"class A { int n = 0; long n = 1; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,10): error CS0102: The type 'A' already contains a definition for 'n' // long n = 1; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "n").WithArguments("A", "n"), // (3,9): warning CS0414: The field 'A.n' is assigned but its value is never used // int n = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n"), // (4,10): warning CS0414: The field 'A.n' is assigned but its value is never used // long n = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n") ); var classA = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; var ns = classA.GetMembers("n"); Assert.Equal(2, ns.Length); foreach (var n in ns) { Assert.Equal(TypeKind.Struct, (n as FieldSymbol).Type.TypeKind); } } [Fact] public void CS0102ERR_DuplicateNameInClass02() { CreateCompilation( @"namespace NS { class C { interface I<T, U> { } interface I<T, U> { } struct S { } public struct S { } } struct S<X> { X x; C x; } } ") .VerifyDiagnostics( // (6,19): error CS0102: The type 'NS.C' already contains a definition for 'I' // interface I<T, U> { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I"), // (9,23): error CS0102: The type 'NS.C' already contains a definition for 'S' // public struct S { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S"), // (14,11): error CS0102: The type 'NS.S<X>' already contains a definition for 'x' // C x; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("NS.S<X>", "x"), // (13,11): warning CS0169: The field 'NS.S<X>.x' is never used // X x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x"), // (14,11): warning CS0169: The field 'NS.S<X>.x' is never used // C x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x") ); // Dev10 miss this with previous errors } [Fact] public void CS0102ERR_DuplicateNameInClass03() { CreateCompilation( @"namespace NS { class C { interface I<T> { } class I<U> { } struct S { } class S { } enum E { } interface E { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I").WithLocation(6, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S").WithLocation(8, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("NS.C", "E").WithLocation(10, 19)); } [Fact] public void CS0104ERR_AmbigContext01() { var text = @"namespace n1 { public interface IGoo<T> { } class A { } } namespace n3 { using n1; using n2; namespace n2 { public interface IGoo<V> { } public class A { } } public class C<X> : IGoo<X> { } struct S { A a; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,9): error CS0104: 'A' is an ambiguous reference between 'n1.A' and 'n3.n2.A' // A a; Diagnostic(ErrorCode.ERR_AmbigContext, "A").WithArguments("A", "n1.A", "n3.n2.A").WithLocation(22, 9), // (16,25): error CS0104: 'IGoo<>' is an ambiguous reference between 'n1.IGoo<T>' and 'n3.n2.IGoo<V>' // public class C<X> : IGoo<X> Diagnostic(ErrorCode.ERR_AmbigContext, "IGoo<X>").WithArguments("IGoo<>", "n1.IGoo<T>", "n3.n2.IGoo<V>").WithLocation(16, 25), // (22,11): warning CS0169: The field 'S.a' is never used // A a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("n3.S.a").WithLocation(22, 11) ); var ns3 = comp.SourceModule.GlobalNamespace.GetMember<NamespaceSymbol>("n3"); var classC = ns3.GetMember<NamedTypeSymbol>("C"); var classCInterface = classC.Interfaces().Single(); Assert.Equal("IGoo", classCInterface.Name); Assert.Equal(TypeKind.Error, classCInterface.TypeKind); var structS = ns3.GetMember<NamedTypeSymbol>("S"); var structSField = structS.GetMember<FieldSymbol>("a"); Assert.Equal("A", structSField.Type.Name); Assert.Equal(TypeKind.Error, structSField.Type.TypeKind); } [Fact] public void CS0106ERR_BadMemberFlag01() { var text = @"namespace MyNamespace { interface I { void m(); static public void f(); } public class MyClass { virtual ushort field; public void I.m() // CS0106 { } } }"; CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (11,24): error CS0106: The modifier 'virtual' is not valid for this item // virtual ushort field; Diagnostic(ErrorCode.ERR_BadMemberFlag, "field").WithArguments("virtual").WithLocation(11, 24), // (12,23): error CS0106: The modifier 'public' is not valid for this item // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_BadMemberFlag, "m").WithArguments("public").WithLocation(12, 23), // (12,21): error CS0540: 'MyClass.I.m()': containing type does not implement interface 'I' // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("MyNamespace.MyClass.MyNamespace.I.m()", "MyNamespace.I").WithLocation(12, 21), // (11,24): warning CS0169: The field 'MyClass.field' is never used // virtual ushort field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("MyNamespace.MyClass.field").WithLocation(11, 24), // (6,28): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "f").WithArguments("static", "7.0", "8.0").WithLocation(6, 28), // (6,28): error CS8503: The modifier 'public' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "f").WithArguments("public", "7.0", "8.0").WithLocation(6, 28), // (6,28): error CS0501: 'I.f()' must declare a body because it is not marked abstract, extern, or partial // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "f").WithArguments("MyNamespace.I.f()").WithLocation(6, 28) ); } [Fact] public void CS0106ERR_BadMemberFlag02() { var text = @"interface I { public static int P1 { get; } abstract int P2 { static set; } int P4 { new abstract get; } int P5 { static set; } int P6 { sealed get; } } class C { public int P1 { virtual get { return 0; } } internal int P2 { static set { } } static int P3 { new get { return 0; } } int P4 { sealed get { return 0; } } protected internal object P5 { get { return null; } extern set; } public extern object P6 { get; } // no error } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (3,23): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // public static int P1 { get; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("static", "7.0", "8.0").WithLocation(3, 23), // (3,23): error CS8503: The modifier 'public' is not valid for this item in C# 7. Please use language version '8.0' or greater. // public static int P1 { get; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("public", "7.0", "8.0").WithLocation(3, 23), // (4,18): error CS8503: The modifier 'abstract' is not valid for this item in C# 7. Please use language version '8.0' or greater. // abstract int P2 { static set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("abstract", "7.0", "8.0").WithLocation(4, 18), // (4,30): error CS0106: The modifier 'static' is not valid for this item // abstract int P2 { static set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(4, 30), // (5,27): error CS0106: The modifier 'abstract' is not valid for this item // int P4 { new abstract get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("abstract").WithLocation(5, 27), // (5,27): error CS0106: The modifier 'new' is not valid for this item // int P4 { new abstract get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("new").WithLocation(5, 27), // (6,21): error CS0106: The modifier 'static' is not valid for this item // int P5 { static set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(6, 21), // (7,21): error CS0106: The modifier 'sealed' is not valid for this item // int P6 { sealed get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("sealed").WithLocation(7, 21), // (11,29): error CS0106: The modifier 'virtual' is not valid for this item // public int P1 { virtual get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("virtual").WithLocation(11, 29), // (12,30): error CS0106: The modifier 'static' is not valid for this item // internal int P2 { static set { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(12, 30), // (13,25): error CS0106: The modifier 'new' is not valid for this item // static int P3 { new get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("new").WithLocation(13, 25), // (14,21): error CS0106: The modifier 'sealed' is not valid for this item // int P4 { sealed get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("sealed").WithLocation(14, 21), // (15,64): error CS0106: The modifier 'extern' is not valid for this item // protected internal object P5 { get { return null; } extern set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("extern").WithLocation(15, 64), // (16,31): warning CS0626: Method, operator, or accessor 'C.P6.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public extern object P6 { get; } // no error Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.P6.get").WithLocation(16, 31) ); } [WorkItem(539584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539584")] [Fact] public void CS0106ERR_BadMemberFlag03() { var text = @" class C { sealed private C() { } new abstract C(object o); public virtual C(C c) { } protected internal override C(int i, int j) { } volatile const int x = 1; } "; CreateCompilation(text).VerifyDiagnostics( // (4,20): error CS0106: The modifier 'sealed' is not valid for this item // sealed private C() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("sealed"), // (5,18): error CS0106: The modifier 'abstract' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,18): error CS0106: The modifier 'new' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("new"), // (6,20): error CS0106: The modifier 'virtual' is not valid for this item // public virtual C(C c) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("virtual"), // (73): error CS0106: The modifier 'override' is not valid for this item // protected internal override C(int i, int j) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("override"), // (8,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile const int x = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile") ); } [Fact] public void CS0106ERR_BadMemberFlag04() { var text = @" class C { static int this[int x] { set { } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 4, Column = 16 }); } [Fact] public void CS0106ERR_BadMemberFlag05() { var text = @" struct Goo { public abstract void Bar1(); public virtual void Bar2() { } public virtual int Bar3 { get;set; } public abstract int Bar4 { get;set; } public abstract event System.EventHandler Bar5; public virtual event System.EventHandler Bar6; // prevent warning for test void OnBar() { Bar6?.Invoke(null, null); } public virtual int this[int x] { get { return 1;} set {;} } // use long for to prevent signature clash public abstract int this[long x] { get; set; } public sealed override string ToString() => null; } "; CreateCompilation(text).VerifyDiagnostics( // (6,24): error CS0106: The modifier 'virtual' is not valid for this item // public virtual int Bar3 { get;set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar3").WithArguments("virtual").WithLocation(6, 24), // (7,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int Bar4 { get;set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar4").WithArguments("abstract").WithLocation(7, 25), // (12,24): error CS0106: The modifier 'virtual' is not valid for this item // public virtual int this[int x] { get { return 1;} set {;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("virtual").WithLocation(12, 24), // (14,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[long x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(14, 25), // (5,25): error CS0106: The modifier 'virtual' is not valid for this item // public virtual void Bar2() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar2").WithArguments("virtual").WithLocation(5, 25), // (4,26): error CS0106: The modifier 'abstract' is not valid for this item // public abstract void Bar1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar1").WithArguments("abstract").WithLocation(4, 26), // (8,47): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.EventHandler Bar5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar5").WithArguments("abstract").WithLocation(8, 47), // (9,46): error CS0106: The modifier 'virtual' is not valid for this item // public virtual event System.EventHandler Bar6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar6").WithArguments("virtual").WithLocation(9, 46), // (15,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(15, 35)); } [Fact] public void CS0106ERR_BadMemberFlag06() { var text = @"interface I { int P1 { get; } int P2 { get; set; } } class C : I { private int I.P1 { get { return 0; } } int I.P2 { private get { return 0; } set {} } } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0106: The modifier 'private' is not valid for this item // private int I.P1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("private").WithLocation(8, 19), // (15,17): error CS0106: The modifier 'private' is not valid for this item // private get { return 0; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private").WithLocation(15, 17) ); } [Fact] public void CS0111ERR_MemberAlreadyExists01() { var text = @"class A { void Test() { } public static void Test() { } // CS0111 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MemberAlreadyExists, Line = 4, Column = 24 }); } [Fact] public void CS0111ERR_MemberAlreadyExists02() { var compilation = CreateCompilation( @"static class S { internal static void E<T>(this T t, object o) where T : new() { } internal static void E<T>(this T t, object o) where T : class { } internal static void E<U>(this U u, object o) { } }"); compilation.VerifyDiagnostics( // (4,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(4, 26), // (5,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(5, 26)); } [Fact] public void CS0111ERR_MemberAlreadyExists03() { var compilation = CreateCompilation( @"class C { object this[object o] { get { return null; } set { } } object this[int x] { get { return null; } } int this[int y] { set { } } object this[object o] { get { return null; } set { } } } interface I { object this[int x, int y] { get; set; } I this[int a, int b] { get; } I this[int a, int b] { set; } I this[object a, object b] { get; } }"); compilation.VerifyDiagnostics( // (5,9): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(5, 9), // (6,12): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(6, 12), // (11,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(11, 7), // (12,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(12, 7)); } [Fact] public void CS0111ERR_MemberAlreadyExists04() { var compilation = CreateCompilation( @" using AliasForI = I; public interface I { int this[int x] { get; set; } } public interface J { int this[int x] { get; set; } } public class C : I, J { int I.this[int x] { get { return 0; } set { } } int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 int J.this[int x] { get { return 0; } set { } } //fine public int this[int x] { get { return 0; } set { } } //fine } "); compilation.VerifyDiagnostics( // (13,14): error CS8646: 'I.this[int]' is explicitly implemented more than once. // public class C : I, J Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C").WithArguments("I.this[int]").WithLocation(13, 14), // (16,19): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types // int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C")); } /// <summary> /// Method signature comparison should ignore constraints. /// </summary> [Fact] public void CS0111ERR_MemberAlreadyExists05() { var compilation = CreateCompilation( @"class C { void M<T>(T t) where T : new() { } void M<U>(U u) where U : struct { } void M<T>(T t) where T : C { } } interface I<T> { void M<U>(); void M<U>() where U : T; }"); compilation.VerifyDiagnostics( // (4,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(4, 10), // (5,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(5, 10), // (10,10): error CS0111: Type 'I<T>' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "I<T>").WithLocation(10, 10)); } [Fact] public void CS0112ERR_StaticNotVirtual01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); } public class MyClass2 : MyClass { override public static void MyMethod() // CS0112, remove static keyword { } public static int Main() { return 0; } } } "; CreateCompilation(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,18): error CS0534: 'MyClass2' does not implement inherited abstract member 'MyClass.MyMethod()' // public class MyClass2 : MyClass Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "MyClass2").WithArguments("MyNamespace.MyClass2", "MyNamespace.MyClass.MyMethod()").WithLocation(7, 18), // (9,37): error CS0112: A static member cannot be marked as 'override' // override public static void MyMethod() // CS0112, remove static keyword Diagnostic(ErrorCode.ERR_StaticNotVirtual, "MyMethod").WithArguments("override").WithLocation(9, 37), // (9,37): warning CS0114: 'MyClass2.MyMethod()' hides inherited member 'MyClass.MyMethod()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // override public static void MyMethod() // CS0112, remove static keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "MyMethod").WithArguments("MyNamespace.MyClass2.MyMethod()", "MyNamespace.MyClass.MyMethod()").WithLocation(9, 37) ); } [Fact] public void CS0112ERR_StaticNotVirtual02() { var text = @"abstract class A { protected abstract object P { get; } } class B : A { protected static override object P { get { return null; } } public static virtual object Q { get; } internal static abstract object R { get; set; } } "; var tree = Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); CreateCompilation(tree).VerifyDiagnostics( // (5,7): error CS0534: 'B' does not implement inherited abstract member 'A.P.get' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P.get").WithLocation(5, 7), // (7,38): error CS0112: A static member cannot be marked as 'override' // protected static override object P { get { return null; } } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P").WithArguments("override").WithLocation(7, 38), // (7,38): warning CS0114: 'B.P' hides inherited member 'A.P'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected static override object P { get { return null; } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "P").WithArguments("B.P", "A.P").WithLocation(7, 38), // (8,34): error CS0112: A static member cannot be marked as 'virtual' // public static virtual object Q { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "Q").WithArguments("virtual").WithLocation(8, 34), // (8,34): error CS8026: Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater. // public static virtual object Q { get; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "Q").WithArguments("readonly automatically implemented properties", "6").WithLocation(8, 34), // (9,37): error CS0112: A static member cannot be marked as 'abstract' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "R").WithArguments("abstract").WithLocation(9, 37), // (9,41): error CS0513: 'B.R.get' is abstract but it is contained in non-abstract type 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("B.R.get", "B").WithLocation(9, 41), // (9,46): error CS0513: 'B.R.set' is abstract but it is contained in non-abstract type 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("B.R.set", "B").WithLocation(9, 46)); } [Fact] public void CS0112ERR_StaticNotVirtual03() { var text = @"abstract class A { protected abstract event System.Action P; } abstract class B : A { protected static override event System.Action P; public static virtual event System.Action Q; internal static abstract event System.Action R; } "; CreateCompilation(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,51): error CS0112: A static member cannot be marked as 'override' // protected static override event System.Action P; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P").WithArguments("override").WithLocation(7, 51), // (7,51): error CS0533: 'B.P' hides inherited abstract member 'A.P' // protected static override event System.Action P; Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("B.P", "A.P").WithLocation(7, 51), // (7,51): warning CS0114: 'B.P' hides inherited member 'A.P'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected static override event System.Action P; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "P").WithArguments("B.P", "A.P").WithLocation(7, 51), // (7,51): warning CS0067: The event 'B.P' is never used // protected static override event System.Action P; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P").WithArguments("B.P").WithLocation(7, 51), // (8,47): error CS0112: A static member cannot be marked as 'virtual' // public static virtual event System.Action Q; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "Q").WithArguments("virtual").WithLocation(8, 47), // (8,47): warning CS0067: The event 'B.Q' is never used // public static virtual event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("B.Q").WithLocation(8, 47), // (9,50): error CS0112: A static member cannot be marked as 'abstract' // internal static abstract event System.Action R; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "R").WithArguments("abstract").WithLocation(9, 50) ); } [Fact] public void CS0113ERR_OverrideNotNew01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); public abstract void MyMethod(int x); public virtual void MyMethod(int x, long j) { } } public class MyClass2 : MyClass { override new public void MyMethod() // CS0113, remove new keyword { } virtual override public void MyMethod(int x) // CS0113, remove virtual keyword { } virtual override public void MyMethod(int x, long j) // CS0113, remove virtual keyword { } public static int Main() { return 0; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 14, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 17, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 20, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew02() { var text = @"abstract class A { protected abstract object P { get; } internal virtual object Q { get; set; } } class B : A { protected new override object P { get { return null; } } internal virtual override object Q { get; set; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 8, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 9, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew03() { var text = @"abstract class A { protected abstract event System.Action P; internal virtual event System.Action Q; } class B : A { protected new override event System.Action P; internal virtual override event System.Action Q; } "; CreateCompilation(text).VerifyDiagnostics( // (9,51): error CS0113: A member 'B.Q' marked as override cannot be marked as new or virtual // internal virtual override event System.Action Q; Diagnostic(ErrorCode.ERR_OverrideNotNew, "Q").WithArguments("B.Q").WithLocation(9, 51), // (8,48): error CS0113: A member 'B.P' marked as override cannot be marked as new or virtual // protected new override event System.Action P; Diagnostic(ErrorCode.ERR_OverrideNotNew, "P").WithArguments("B.P").WithLocation(8, 48), // (8,48): warning CS0067: The event 'B.P' is never used // protected new override event System.Action P; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P").WithArguments("B.P").WithLocation(8, 48), // (9,51): warning CS0067: The event 'B.Q' is never used // internal virtual override event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("B.Q").WithLocation(9, 51), // (4,42): warning CS0067: The event 'A.Q' is never used // internal virtual event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("A.Q").WithLocation(4, 42)); } [Fact] public void CS0115ERR_OverrideNotExpected() { var text = @"namespace MyNamespace { abstract public class MyClass1 { public abstract int f(); } abstract public class MyClass2 { public override int f() // CS0115 { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 29 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0118ERR_BadSKknown01() { var text = @"namespace NS { namespace Goo {} internal struct S { void Goo(Goo f) {} } class Bar { Goo foundNamespaceInsteadOfType; } public class A : Goo {} }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,18): error CS0118: 'Goo' is a namespace but is used like a type // void Goo(Goo f) {} Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (12,9): error CS0118: 'Goo' is a namespace but is used like a type // Goo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (15,22): error CS0118: 'Goo' is a namespace but is used like a type // public class A : Goo {} Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (12,13): warning CS0169: The field 'NS.Bar.foundNamespaceInsteadOfType' is never used // Goo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.WRN_UnreferencedField, "foundNamespaceInsteadOfType").WithArguments("NS.Bar.foundNamespaceInsteadOfType") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = ns.GetTypeMembers("A").Single().BaseType(); Assert.Equal("Goo", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); Assert.Null(baseType.BaseType()); var type2 = ns.GetTypeMembers("Bar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers("foundNamespaceInsteadOfType").Single() as FieldSymbol; Assert.Equal("Goo", mem1.Type.Name); Assert.Equal(TypeKind.Error, mem1.Type.TypeKind); var type3 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type3.GetMembers("Goo").Single() as MethodSymbol; var param = mem2.Parameters[0]; Assert.Equal("Goo", param.Type.Name); Assert.Equal(TypeKind.Error, param.Type.TypeKind); } [WorkItem(538147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538147")] [Fact] public void CS0118ERR_BadSKknown02() { var text = @" class Test { static void Main() { B B = null; if (B == B) {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadSKknown, Line = 6, Column = 10 }); } [Fact] public void CS0119ERR_BadSKunknown01() { var text = @"namespace NS { using System; public class Test { public static void F() { } public static int Main() { Console.WriteLine(F.x); return NS(); } } }"; CreateCompilation(text).VerifyDiagnostics( // (10,31): error CS0119: 'NS.Test.F()' is a method, which is not valid in the given context // Console.WriteLine(F.x); Diagnostic(ErrorCode.ERR_BadSKunknown, "F").WithArguments("NS.Test.F()", "method"), // (11,20): error CS0118: 'NS' is a namespace but is used like a variable // return NS(); Diagnostic(ErrorCode.ERR_BadSKknown, "NS").WithArguments("NS", "namespace", "variable") ); } [Fact, WorkItem(538214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214")] public void CS0119ERR_BadSKunknown02() { var text = @"namespace N1 { class Test { static void Main() { double x = -5d; int y = (global::System.Int32) +x; short z = (System.Int16) +x; } } } "; // Roslyn gives same error twice CreateCompilation(text).VerifyDiagnostics( // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type") ); } [Fact] public void CS0132ERR_StaticConstParam01() { var text = @"namespace NS { struct S { static S(string s) { } } public class clx { static clx(params long[] ary) { } static clx(ref int n) { } } public class cly : clx { static cly() { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 10, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 11, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(539627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539627")] [Fact] public void CS0136ERR_LocalIllegallyOverrides() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @" class MyClass { public MyClass(int a) { long a; // 0136 } public long MyMeth(string x) { long x = 1; // 0136 return x; } public byte MyProp { set { int value; // 0136 } } } "; CreateCompilation(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "a").WithArguments("a"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "value").WithArguments("value") ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @"class C { public static void Main() { foreach (var x in ""abc"") { int x = 1 ; System.Console.WriteLine(x); } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x")); } [Fact] public void CS0138ERR_BadUsingNamespace01() { var text = @"using System.Object; namespace NS { using NS.S; struct S {} }"; var comp = CreateCompilation(Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); comp.VerifyDiagnostics( // (1,7): error CS0138: A using namespace directive can only be applied to namespaces; 'object' is a type not a namespace // using System.Object; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System.Object").WithArguments("object"), // (5,11): error CS0138: A using namespace directive can only be applied to namespaces; 'NS.S' is a type not a namespace // using NS.S; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "NS.S").WithArguments("NS.S"), // (1,1): info CS8019: Unnecessary using directive. // using System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Object;"), // (5,5): info CS8019: Unnecessary using directive. // using NS.S; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NS.S;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Roslyn has 3 extra CS0146, Neal said it's per spec /// </summary> [Fact] public void CS0146ERR_CircularBase01() { var text = @"namespace NS { class A : B { } class B : A { } public class AA : BB { } public class BB : CC { } public class CC : DD { } public class DD : BB { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 3, Column = 11 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 7, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 8, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 9, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = (NamedTypeSymbol)ns.GetTypeMembers("A").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("B", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("DD").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("BB", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("BB").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("CC", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); } [Fact] public void CS0146ERR_CircularBase02() { var text = @"public interface C<T> { } public class D : C<D.Q> { private class Q { } // accessible in base clause } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase03() { var text = @" class A : object, A.IC { protected interface IC { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase04() { var text = @" class A : object, I<A.IC> { protected interface IC { } } interface I<T> { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0179ERR_ExternHasBody01() { var text = @" namespace NS { public class C { extern C() { } extern void M1() { } extern int M2() => 1; extern object P1 { get { return null; } set { } } extern int P2 => 1; extern event System.Action E { add { } remove { } } extern static public int operator + (C c1, C c2) { return 1; } extern static public int operator - (C c1, C c2) => 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,16): error CS0179: 'C.C()' cannot be extern and declare a body // extern C() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "C").WithArguments("NS.C.C()").WithLocation(6, 16), // (7,21): error CS0179: 'C.M1()' cannot be extern and declare a body // extern void M1() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "M1").WithArguments("NS.C.M1()").WithLocation(7, 21), // (8,20): error CS0179: 'C.M2()' cannot be extern and declare a body // extern int M2() => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "M2").WithArguments("NS.C.M2()").WithLocation(8, 20), // (9,28): error CS0179: 'C.P1.get' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("NS.C.P1.get").WithLocation(9, 28), // (9,49): error CS0179: 'C.P1.set' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("NS.C.P1.set").WithLocation(9, 49), // (10,26): error CS0179: 'C.P2.get' cannot be extern and declare a body // extern int P2 => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "1").WithArguments("NS.C.P2.get").WithLocation(10, 26), // (11,40): error CS0179: 'C.E.add' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("NS.C.E.add").WithLocation(11, 40), // (11,48): error CS0179: 'C.E.remove' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("NS.C.E.remove").WithLocation(11, 48), // (12,43): error CS0179: 'C.operator +(C, C)' cannot be extern and declare a body // extern static public int operator + (C c1, C c2) { return 1; } Diagnostic(ErrorCode.ERR_ExternHasBody, "+").WithArguments("NS.C.operator +(NS.C, NS.C)").WithLocation(12, 43), // (13,43): error CS0179: 'C.operator -(C, C)' cannot be extern and declare a body // extern static public int operator - (C c1, C c2) => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "-").WithArguments("NS.C.operator -(NS.C, NS.C)").WithLocation(13, 43)); } [Fact] public void CS0180ERR_AbstractAndExtern01() { CreateCompilation( @"abstract class X { public abstract extern void M(); public extern abstract int P { get; } // If a body is provided for an abstract extern method, // Dev10 reports CS0180, but does not report CS0179/CS0500. public abstract extern void N(int i) { } public extern abstract object Q { set { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("X.M()").WithLocation(3, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("X.P").WithLocation(4, 32), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "N").WithArguments("X.N(int)").WithLocation(7, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "Q").WithArguments("X.Q").WithLocation(8, 35)); } [WorkItem(527618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527618")] [Fact] public void CS0180ERR_AbstractAndExtern02() { CreateCompilation( @"abstract class C { public extern abstract void M(); public extern abstract object P { set; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("C.M()"), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("C.P")); } [Fact] public void CS0180ERR_AbstractAndExtern03() { CreateCompilation( @"class C { public extern abstract event System.Action E; } ") .VerifyDiagnostics( // (3,48): error CS0180: 'C.E' cannot be both extern and abstract // public extern abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E").WithArguments("C.E")); } [Fact] public void CS0181ERR_BadAttributeParamType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1] // Dev11 error public class A1 : Attribute { public A1(dynamic i = null) { } } [A2] // Dev11 ok (bug) public class A2 : Attribute { public A2(dynamic[] i = null) { } } [A3] // Dev11 error (bug) public class A3 : Attribute { public A3(C<dynamic>.D i = 0) { } } [A4] // Dev11 ok public class A4 : Attribute { public A4(C<dynamic>.D[] i = null) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic', which is not a valid attribute parameter type // [A1] // Dev11 error Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A1").WithArguments("i", "dynamic"), // (12,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic[]', which is not a valid attribute parameter type // [A2] // Dev11 ok Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A2").WithArguments("i", "dynamic[]")); } [Fact] public void CS0182ERR_BadAttributeArgument() { var text = @"public class MyClass { static string s = ""Test""; [System.Diagnostics.ConditionalAttribute(s)] // CS0182 void NonConstantArgumentToConditional() { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,46): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [System.Diagnostics.ConditionalAttribute(s)] // CS0182 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s"), // (3,19): warning CS0414: The field 'MyClass.s' is assigned but its value is never used // static string s = "Test"; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("MyClass.s")); } [Fact] public void CS0214ERR_UnsafeNeeded() { var text = @"public struct S { public int a; } public class MyClass { public static void Test() { S s = new S(); S* s2 = &s; // CS0214 s2->a = 3; // CS0214 s.a = 0; } // OK unsafe public static void Test2() { S s = new S(); S* s2 = &s; s2->a = 3; s.a = 0; } } "; // NOTE: only first in scope is reported. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "S*"), // (11,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&s"), // (12,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s2->a = 3; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s2")); } [Fact] public void CS0214ERR_UnsafeNeeded02() { var text = @"unsafe struct S { public fixed int x[10]; } class Program { static void Main() { S s; s.x[1] = s.x[2]; } }"; // NOTE: only first in scope is reported. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x"), // (11,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x")); } [Fact] public void CS0214ERR_UnsafeNeeded03() { var text = @"public struct S { public fixed int buf[10]; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed int buf[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "buf[10]")); } [Fact] public void CS0214ERR_UnsafeNeeded04() { var text = @" namespace System { public class TestType { public void TestMethod() { var x = stackalloc int[10]; // ERROR Span<int> y = stackalloc int[10]; // OK } } } "; CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = stackalloc int[10]; // ERROR Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[10]").WithLocation(8, 21)); } [Fact] public void CS0215ERR_OpTFRetType() { var text = @"class MyClass { public static int operator true(MyClass MyInt) // CS0215 { return 1; } public static int operator false(MyClass MyInt) // CS0215 { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,32): error CS0215: The return type of operator True or False must be bool // public static int operator true(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "true"), // (8,32): error CS0215: The return type of operator True or False must be bool // public static int operator false(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "false") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch() { var text = @"class MyClass { // Missing operator false public static bool operator true(MyClass MyInt) // CS0216 { return true; } // Missing matching operator > -- parameter types must match. public static bool operator < (MyClass x, int y) { return false; } // Missing matching operator < -- parameter types must match. public static bool operator > (MyClass x, double y) { return false; } // Missing matching operator >= -- return types must match. public static MyClass operator <=(MyClass x, MyClass y) { return x; } // Missing matching operator <= -- return types must match. public static bool operator >=(MyClass x, MyClass y) { return true; } // Missing operator != public static bool operator ==(MyClass x, MyClass y) { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): warning CS0660: 'MyClass' defines operator == or operator != but does not override Object.Equals(object o) // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "MyClass").WithArguments("MyClass"), // (1,7): warning CS0661: 'MyClass' defines operator == or operator != but does not override Object.GetHashCode() // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "MyClass").WithArguments("MyClass"), // (4,33): error CS0216: The operator 'MyClass.operator true(MyClass)' requires a matching operator 'false' to also be defined // public static bool operator true(MyClass MyInt) // CS0216 Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("MyClass.operator true(MyClass)", "false"), // (73): error CS0216: The operator 'MyClass.operator <(MyClass, int)' requires a matching operator '>' to also be defined // public static bool operator < (MyClass x, int y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<").WithArguments("MyClass.operator <(MyClass, int)", ">"), // (10,33): error CS0216: The operator 'MyClass.operator >(MyClass, double)' requires a matching operator '<' to also be defined // public static bool operator > (MyClass x, double y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">").WithArguments("MyClass.operator >(MyClass, double)", "<"), // (13,36): error CS0216: The operator 'MyClass.operator <=(MyClass, MyClass)' requires a matching operator '>=' to also be defined // public static MyClass operator <=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<=").WithArguments("MyClass.operator <=(MyClass, MyClass)", ">="), // (16,33): error CS0216: The operator 'MyClass.operator >=(MyClass, MyClass)' requires a matching operator '<=' to also be defined // public static bool operator >=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">=").WithArguments("MyClass.operator >=(MyClass, MyClass)", "<="), // (19,33): error CS0216: The operator 'MyClass.operator ==(MyClass, MyClass)' requires a matching operator '!=' to also be defined // public static bool operator ==(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "==").WithArguments("MyClass.operator ==(MyClass, MyClass)", "!=") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch_NoErrorForDynamicObject() { string source = @" using System.Collections.Generic; class C { public static object operator >(C p1, dynamic p2) { return null; } public static dynamic operator <(C p1, object p2) { return null; } public static dynamic operator >=(C p1, dynamic p2) { return null; } public static object operator <=(C p1, object p2) { return null; } public static List<object> operator ==(C p1, dynamic[] p2) { return null; } public static List<dynamic> operator !=(C p1, object[] p2) { return null; } public override bool Equals(object o) { return false; } public override int GetHashCode() { return 1; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0218ERR_MustHaveOpTF() { // Note that the wording of this error has changed. var text = @" public class MyClass { public static MyClass operator &(MyClass f1, MyClass f2) { return new MyClass(); } public static void Main() { MyClass f = new MyClass(); MyClass i = f && f; // CS0218, requires operators true and false } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,21): error CS0218: In order to be applicable as a short circuit operator, the declaring type 'MyClass' of user-defined operator 'MyClass.operator &(MyClass, MyClass)' must declare operator true and operator false. // MyClass i = f && f; // CS0218, requires operators true and false Diagnostic(ErrorCode.ERR_MustHaveOpTF, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)", "MyClass") ); } [Fact] public void CS0224ERR_BadVarargs01() { var text = @"namespace NS { class C { public static void F<T>(T x, __arglist) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 5, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0224ERR_BadVarargs02() { var text = @"class C { C(object o, __arglist) { } // no error void M(__arglist) { } // no error } abstract class C<T> { C(object o) { } // no error C(__arglist) { } void M(object o, __arglist) { } internal abstract object F(__arglist); } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 9, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 10, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 11, Column = 30 }); } [Fact] public void CS0225ERR_ParamsMustBeArray01() { var text = @" using System.Collections.Generic; public class A { struct S { internal List<string> Bar(string s1, params List<string> s2) { return s2; } } public static void Goo(params int a) {} public static int Main() { Goo(1); return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 8, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 13, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; // TODO... } [Fact] public void CS0227ERR_IllegalUnsafe() { var text = @"public class MyClass { unsafe public static void Main() // CS0227 { } } "; var c = CreateCompilation(text, options: TestOptions.ReleaseDll.WithAllowUnsafe(false)); c.VerifyDiagnostics( // (3,31): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe public static void Main() // CS0227 Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Main").WithLocation(3, 31)); } [Fact] public void CS0234ERR_DottedTypeNameNotFoundInNS() { var text = @"using NA = N.A; using NB = C<N.B<object>>; namespace N { } class C<T> { NA a; NB b; N.C<N.D> c; }"; CreateCompilation(text).VerifyDiagnostics( // (2,16): error CS0234: The type or namespace name 'B<>' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NB = C<N.B<object>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "B<object>").WithArguments("B<>", "N").WithLocation(2, 16), // (1,14): error CS0234: The type or namespace name 'A' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NA = N.A; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "A").WithArguments("A", "N").WithLocation(1, 14), // (8,7): error CS0234: The type or namespace name 'C<>' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C<N.D>").WithArguments("C<>", "N").WithLocation(8, 7), // (8,11): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "D").WithArguments("D", "N").WithLocation(8, 11), // (6,8): warning CS0169: The field 'C<T>.a' is never used // NA a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C<T>.a").WithLocation(6, 8), // (7,8): warning CS0169: The field 'C<T>.b' is never used // NB b; Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b").WithLocation(7, 8), // (8,14): warning CS0169: The field 'C<T>.c' is never used // N.C<N.D> c; Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c").WithLocation(8, 14) ); } [Fact] public void CS0238ERR_SealedNonOverride01() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public sealed void f() // CS0238 { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 24, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 7 }); } [Fact] public void CS0238ERR_SealedNonOverride02() { var text = @"interface I { sealed void M(); sealed object P { get; } } "; //we're diverging from Dev10 - it's a little silly to report two errors saying the same modifier isn't allowed CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (3,17): error CS8503: The modifier 'sealed' is not valid for this item in C# 7. Please use language version '8.0' or greater. // sealed void M(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M").WithArguments("sealed", "7.0", "8.0").WithLocation(3, 17), // (4,19): error CS8503: The modifier 'sealed' is not valid for this item in C# 7. Please use language version '8.0' or greater. // sealed object P { get; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P").WithArguments("sealed", "7.0", "8.0").WithLocation(4, 19), // (4,23): error CS0501: 'I.P.get' must declare a body because it is not marked abstract, extern, or partial // sealed object P { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I.P.get").WithLocation(4, 23), // (3,17): error CS0501: 'I.M()' must declare a body because it is not marked abstract, extern, or partial // sealed void M(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("I.M()").WithLocation(3, 17) ); } [Fact] public void CS0238ERR_SealedNonOverride03() { var text = @"class B { sealed int P { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 3, Column = 16 }); } [Fact] public void CS0238ERR_SealedNonOverride04() { var text = @"class B { sealed event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (3,32): error CS0238: 'B.E' cannot be sealed because it is not an override // sealed event System.Action E; Diagnostic(ErrorCode.ERR_SealedNonOverride, "E").WithArguments("B.E"), // (3,32): warning CS0067: The event 'B.E' is never used // sealed event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B.E")); } [Fact] public void CS0239ERR_CantOverrideSealed() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public override sealed void f() { } } class MyClass3 : MyClass2 { public override void f() // CS0239 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 19, Column = 26 }); } [Fact()] public void CS0243ERR_ConditionalOnOverride() { var text = @"public class MyClass { public virtual void M() { } } public class MyClass2 : MyClass { [System.Diagnostics.ConditionalAttribute(""MySymbol"")] // CS0243 public override void M() { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,6): error CS0243: The Conditional attribute is not valid on 'MyClass2.M()' because it is an override method // [System.Diagnostics.ConditionalAttribute("MySymbol")] // CS0243 Diagnostic(ErrorCode.ERR_ConditionalOnOverride, @"System.Diagnostics.ConditionalAttribute(""MySymbol"")").WithArguments("MyClass2.M()").WithLocation(8, 6)); } [Fact] public void CS0246ERR_SingleTypeNameNotFound01() { var text = @"namespace NS { interface IGoo : INotExist {} // Extra CS0527 interface IBar { string M(ref NoType p1, out NoType p2, params NOType[] ary); } class A : CNotExist {} struct S { public const NoType field = 123; private NoType M() { return null; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 51 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 8, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 11, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 12, Column = 14 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("IGoo").Single() as NamedTypeSymbol; // bug: expected 1 but error symbol // Assert.Equal(1, type1.Interfaces().Count()); var type2 = ns.GetTypeMembers("IBar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers().First() as MethodSymbol; //ErrorTypes now appear as though they are declared in the global namespace. Assert.Equal("System.String NS.IBar.M(ref NoType p1, out NoType p2, params NOType[] ary)", mem1.ToTestDisplayString()); var param = mem1.Parameters[0] as ParameterSymbol; var ptype = param.TypeWithAnnotations; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal(TypeKind.Error, ptype.Type.TypeKind); Assert.Equal("NoType", ptype.Type.Name); var type3 = ns.GetTypeMembers("A").Single() as NamedTypeSymbol; var base1 = type3.BaseType(); Assert.Null(base1.BaseType()); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("CNotExist", base1.Name); var type4 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type4.GetMembers("field").First() as FieldSymbol; Assert.Equal(TypeKind.Error, mem2.Type.TypeKind); Assert.Equal("NoType", mem2.Type.Name); var mem3 = type4.GetMembers("M").Single() as MethodSymbol; Assert.Equal(TypeKind.Error, mem3.ReturnType.TypeKind); Assert.Equal("NoType", mem3.ReturnType.Name); } [WorkItem(537882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537882")] [Fact] public void CS0246ERR_SingleTypeNameNotFound02() { var text = @"using NoExistNS1; namespace NS { using NoExistNS2; // No error for this one class Test { static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): error CS0246: The type or namespace name 'NoExistNS1' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS1").WithArguments("NoExistNS1"), // (5,11): error CS0246: The type or namespace name 'NoExistNS2' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS2").WithArguments("NoExistNS2"), // (1,1): info CS8019: Unnecessary using directive. // using NoExistNS1; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS1;"), // (5,5): info CS8019: Unnecessary using directive. // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS2;")); } [Fact] public void CS0246ERR_SingleTypeNameNotFound03() { var text = @"[Attribute] class C { } "; CreateCompilation(text).VerifyDiagnostics( // (1,2): error CS0246: The type or namespace name 'AttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [Attribute] class C { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("AttributeAttribute").WithLocation(1, 2), // (1,2): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) // [Attribute] class C { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute").WithLocation(1, 2)); } [Fact] public void CS0246ERR_SingleTypeNameNotFound04() { var text = @"class AAttribute : System.Attribute { } class BAttribute : System.Attribute { } [A][@B] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 5 }); } [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { var text = @"class C { static void Main(string[] args) { System.Console.WriteLine(typeof(s)); // Invalid } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "s").WithArguments("s")); } [WorkItem(543791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543791")] [Fact] public void CS0246ERR_SingleTypeNameNotFound06() { var text = @"class C { public static Nada x = null, y = null; } "; CreateCompilation(text).VerifyDiagnostics( // (3,19): error CS0246: The type or namespace name 'Nada' could not be found (are you missing a using directive or an assembly reference?) // public static Nada x = null, y = null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nada").WithArguments("Nada") ); } [Fact] public void CS0249ERR_OverrideFinalizeDeprecated() { var text = @"class MyClass { protected override void Finalize() // CS0249 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,29): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (3,29): error CS0249: Do not override object.Finalize. Instead, provide a destructor. Diagnostic(ErrorCode.ERR_OverrideFinalizeDeprecated, "Finalize")); } [Fact] public void CS0260ERR_MissingPartial01() { var text = @"namespace NS { public class C // CS0260 { partial struct S { } struct S { } // CS0260 } public partial class C {} public partial class C {} partial interface I {} interface I { } // CS0260 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 3, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 6, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 13, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0261ERR_PartialTypeKindConflict01() { var text = @"namespace NS { partial class A { } partial class A { } partial struct A { } // CS0261 partial interface A { } // CS0261 partial class B { } partial struct B<T> { } partial interface B<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 5, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 6, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0262ERR_PartialModifierConflict01() { var text = @"namespace NS { public partial interface I { } internal partial interface I { } partial interface I { } class A { internal partial class C { } protected partial class C {} private partial struct S { } internal partial struct S { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,30): error CS0262: Partial declarations of 'I' have conflicting accessibility modifiers // public partial interface I { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "I").WithArguments("NS.I").WithLocation(3, 30), // (9,32): error CS0262: Partial declarations of 'A.C' have conflicting accessibility modifiers // internal partial class C { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "C").WithArguments("NS.A.C").WithLocation(9, 32), // (12,32): error CS0262: Partial declarations of 'A.S' have conflicting accessibility modifiers // private partial struct S { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "S").WithArguments("NS.A.S").WithLocation(12, 32) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0263ERR_PartialMultipleBases01() { var text = @"namespace NS { class B1 { } class B2 { } partial class C : B1 // CS0263 - is the base class B1 or B2? { } partial class C : B2 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 5, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; var base1 = type1.BaseType(); Assert.Null(base1.BaseType()); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("B1", base1.Name); } [Fact] public void ERRMixed_BaseAnalysisMishmash() { var text = @"namespace NS { public interface I { } public class C { } public class D { } public struct S { } public struct N0 : object, NS.C { } public class N1 : C, D { } public struct N2 : C, D { } public class N3 : I, C { } public partial class N4 : C { } public partial class N4 : D { } class N5<T> : C, D { } class N6<T> : C, T { } class N7<T> : T, C { } interface N8 : I, I { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 10, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 13, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 16, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 17, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 18, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 18, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 20, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0264ERR_PartialWrongTypeParams01() { var text = @"namespace NS { public partial class C<T1> // CS0264.cs { } partial class C<T2> { partial struct S<X> { } // CS0264.cs partial struct S<T2> { } } internal partial interface IGoo<T, V> { } // CS0264.cs partial interface IGoo<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 3, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 9, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 13, Column = 32 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; Assert.Equal(1, type1.TypeParameters.Length); var param = type1.TypeParameters[0]; // Assert.Equal(TypeKind.Error, param.TypeKind); // this assert it incorrect: it is definitely a type parameter Assert.Equal("T1", param.Name); } [Fact] public void PartialMethodRenameParameters() { var text = @"namespace NS { public partial class MyClass { partial void F<T, U>(T t) where T : class; partial void F<T, U>(T tt) where T : class {} } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,22): warning CS8826: Partial method declarations 'void MyClass.F<T, U>(T t)' and 'void MyClass.F<T, U>(T tt)' have signature differences. // partial void F<T, U>(T tt) where T : class {} Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F").WithArguments("void MyClass.F<T, U>(T t)", "void MyClass.F<T, U>(T tt)").WithLocation(6, 22) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("MyClass").Single() as NamedTypeSymbol; Assert.Equal(0, type1.TypeParameters.Length); var f = type1.GetMembers("F").Single() as MethodSymbol; Assert.Equal("T t", f.Parameters[0].ToTestDisplayString()); } [Fact] public void PartialMethodRenameTypeParameters() { var text = @"namespace NS { public partial class MyClass { partial void F<T, U>(T t) where T : class; partial void F<U, T>(U u) where U : class {} } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,22): warning CS8826: Partial method declarations 'void MyClass.F<T, U>(T t)' and 'void MyClass.F<U, T>(U u)' have signature differences. // partial void F<U, T>(U u) where U : class {} Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F").WithArguments("void MyClass.F<T, U>(T t)", "void MyClass.F<U, T>(U u)").WithLocation(6, 22) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("MyClass").Single() as NamedTypeSymbol; Assert.Equal(0, type1.TypeParameters.Length); var f = type1.GetMembers("F").Single() as MethodSymbol; Assert.Equal(2, f.TypeParameters.Length); var param1 = f.TypeParameters[0]; var param2 = f.TypeParameters[1]; Assert.Equal("T", param1.Name); Assert.Equal("U", param2.Name); } [Fact] public void CS0265ERR_PartialWrongConstraints01() { var text = @"interface IA<T> { } interface IB { } // Different constraints. partial class A1<T> where T : struct { } partial class A1<T> where T : class { } partial class A2<T, U> where T : struct where U : IA<T> { } partial class A2<T, U> where T : class where U : IB { } partial class A3<T> where T : IA<T> { } partial class A3<T> where T : IA<IA<T>> { } partial interface A4<T> where T : struct, IB { } partial interface A4<T> where T : class, IB { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IB, new() { } // Additional constraints. partial class B1<T> where T : new() { } partial class B1<T> where T : class, new() { } partial class B2<T, U> where T : IA<T> { } partial class B2<T, U> where T : IB, IA<T> { } // Missing constraints. partial interface C1<T> where T : class, new() { } partial interface C1<T> where T : new() { } partial struct C2<T, U> where U : IB, IA<T> { } partial struct C2<T, U> where U : IA<T> { } // Same constraints, different order. partial class D1<T> where T : IA<T>, IB { } partial class D1<T> where T : IB, IA<T> { } partial class D1<T> where T : IA<T>, IB { } partial class D2<T, U, V> where V : T, U { } partial class D2<T, U, V> where V : U, T { } // Different constraint clauses. partial class E1<T, U> where U : T { } partial class E1<T, U> where T : class { } partial class E1<T, U> where U : T { } partial class E2<T, U> where U : IB { } partial class E2<T, U> where T : IA<U> { } partial class E2<T, U> where T : IA<U> { } // Additional constraint clause. partial class F1<T> { } partial class F1<T> { } partial class F1<T> where T : class { } partial class F2<T> { } partial class F2<T, U> where T : class { } partial class F2<T, U> where T : class where U : T { } // Missing constraint clause. partial interface G1<T> where T : class { } partial interface G1<T> { } partial struct G2<T, U> where T : class where U : T { } partial struct G2<T, U> where T : class { } partial struct G2<T, U> { } // Same constraint clauses, different order. partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where U : T where T : class { } partial class H2<T, U, V> where U : IB where T : IA<V> { } partial class H2<T, U, V> where T : IA<V> where U : IB { }"; CreateCompilation(text).VerifyDiagnostics( // (4,15): error CS0265: Partial declarations of 'A1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A1").WithArguments("A1<T>", "T").WithLocation(4, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "T").WithLocation(6, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "U").WithLocation(6, 15), // (8,15): error CS0265: Partial declarations of 'A3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A3").WithArguments("A3<T>", "T").WithLocation(8, 15), // (10,19): error CS0265: Partial declarations of 'A4<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A4").WithArguments("A4<T>", "T").WithLocation(10, 19), // (12,16): error CS0265: Partial declarations of 'A5<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A5").WithArguments("A5<T>", "T").WithLocation(12, 16), // (16,15): error CS0265: Partial declarations of 'B1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B1").WithArguments("B1<T>", "T").WithLocation(16, 15), // (18,15): error CS0265: Partial declarations of 'B2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B2").WithArguments("B2<T, U>", "T").WithLocation(18, 15), // (21,19): error CS0265: Partial declarations of 'C1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C1").WithArguments("C1<T>", "T").WithLocation(21, 19), // (23,16): error CS0265: Partial declarations of 'C2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C2").WithArguments("C2<T, U>", "U").WithLocation(23, 16), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "T").WithLocation(32, 15), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "U").WithLocation(32, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "T").WithLocation(35, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "U").WithLocation(35, 15), // (43,15): error CS0265: Partial declarations of 'F2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "F2").WithArguments("F2<T, U>", "U").WithLocation(43, 15), // (48,16): error CS0265: Partial declarations of 'G2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "G2").WithArguments("G2<T, U>", "U").WithLocation(48, 16)); } [Fact] public void CS0265ERR_PartialWrongConstraints02() { var text = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class B1<T> where T : A, IB<IA> { } partial class B1<T> where T : N.A, N.IB<N.IA> { } partial class B1<T> where T : NA1, NIBA { } partial class B2<T> where T : NA1, IB<A.IC> { } partial class B2<T> where T : NA2, NIBAC { } partial class B3<T> where T : IB<A> { } partial class B3<T> where T : NIBA { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,19): error CS0265: Partial declarations of 'N.B3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B3").WithArguments("N.B3<T>", "T").WithLocation(19, 19), // (1,1): info CS8019: Unnecessary using directive. // using NIA = N.IA; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NIA = N.IA;").WithLocation(1, 1)); } /// <summary> /// Class1.dll: error CS0268: Imported type 'C1' is invalid. It contains a circular base type dependency. /// </summary> [Fact()] public void CS0268ERR_ImportedCircularBase01() { var text = @"namespace NS { public class C3 : C1 { } public interface I3 : I1 { } } "; var ref1 = TestReferences.SymbolsTests.CyclicInheritance.Class1; var ref2 = TestReferences.SymbolsTests.CyclicInheritance.Class2; var comp = CreateCompilation(text, new[] { ref1, ref2 }); comp.VerifyDiagnostics( // (3,23): error CS0268: Imported type 'C2' is invalid. It contains a circular base type dependency. // public class C3 : C1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "C1").WithArguments("C2", "C1"), // (4,22): error CS0268: Imported type 'I2' is invalid. It contains a circular base type dependency. // public interface I3 : I1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "I3").WithArguments("I2", "I1") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0273ERR_InvalidPropertyAccessMod() { var text = @"class C { public object P1 { get; public set; } // CS0273 public object P2 { get; internal set; } public object P3 { get; protected set; } public object P4 { get; protected internal set; } public object P5 { get; private set; } internal object Q1 { public get; set; } // CS0273 internal object Q2 { internal get; set; } // CS0273 internal object Q3 { protected get; set; } // CS0273 internal object Q4 { protected internal get; set; } // CS0273 internal object Q5 { private get; set; } protected object R1 { get { return null; } public set { } } // CS0273 protected object R2 { get { return null; } internal set { } } // CS0273 protected object R3 { get { return null; } protected set { } } // CS0273 protected object R4 { get { return null; } protected internal set { } } // CS0273 protected object R5 { get { return null; } private set { } } protected internal object S1 { get { return null; } public set { } } // CS0273 protected internal object S2 { get { return null; } internal set { } } protected internal object S3 { get { return null; } protected set { } } protected internal object S4 { get { return null; } protected internal set { } } // CS0273 protected internal object S5 { get { return null; } private set { } } private object T1 { public get; set; } // CS0273 private object T2 { internal get; set; } // CS0273 private object T3 { protected get; set; } // CS0273 private object T4 { protected internal get; set; } // CS0273 private object T5 { private get; set; } // CS0273 object U1 { public get; set; } // CS0273 object U2 { internal get; set; } // CS0273 object U3 { protected get; set; } // CS0273 object U4 { protected internal get; set; } // CS0273 object U5 { private get; set; } // CS0273 } "; CreateCompilation(text).VerifyDiagnostics( // (3,36): error CS0273: The accessibility modifier of the 'C.P1.set' accessor must be more restrictive than the property or indexer 'C.P1' // public object P1 { get; public set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.P1.set", "C.P1"), // (8,33): error CS0273: The accessibility modifier of the 'C.Q1.get' accessor must be more restrictive than the property or indexer 'C.Q1' // internal object Q1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q1.get", "C.Q1"), // (9,35): error CS0273: The accessibility modifier of the 'C.Q2.get' accessor must be more restrictive than the property or indexer 'C.Q2' // internal object Q2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q2.get", "C.Q2"), // (10,36): error CS0273: The accessibility modifier of the 'C.Q3.get' accessor must be more restrictive than the property or indexer 'C.Q3' // internal object Q3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q3.get", "C.Q3"), // (11,45): error CS0273: The accessibility modifier of the 'C.Q4.get' accessor must be more restrictive than the property or indexer 'C.Q4' // internal object Q4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q4.get", "C.Q4"), // (13,55): error CS0273: The accessibility modifier of the 'C.R1.set' accessor must be more restrictive than the property or indexer 'C.R1' // protected object R1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R1.set", "C.R1"), // (14,57): error CS0273: The accessibility modifier of the 'C.R2.set' accessor must be more restrictive than the property or indexer 'C.R2' // protected object R2 { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R2.set", "C.R2"), // (15,58): error CS0273: The accessibility modifier of the 'C.R3.set' accessor must be more restrictive than the property or indexer 'C.R3' // protected object R3 { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R3.set", "C.R3"), // (16,67): error CS0273: The accessibility modifier of the 'C.R4.set' accessor must be more restrictive than the property or indexer 'C.R4' // protected object R4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R4.set", "C.R4"), // (18,64): error CS0273: The accessibility modifier of the 'C.S1.set' accessor must be more restrictive than the property or indexer 'C.S1' // protected internal object S1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S1.set", "C.S1"), // (21,76): error CS0273: The accessibility modifier of the 'C.S4.set' accessor must be more restrictive than the property or indexer 'C.S4' // protected internal object S4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S4.set", "C.S4"), // (23,32): error CS0273: The accessibility modifier of the 'C.T1.get' accessor must be more restrictive than the property or indexer 'C.T1' // private object T1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T1.get", "C.T1"), // (24,34): error CS0273: The accessibility modifier of the 'C.T2.get' accessor must be more restrictive than the property or indexer 'C.T2' // private object T2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T2.get", "C.T2"), // (25,35): error CS0273: The accessibility modifier of the 'C.T3.get' accessor must be more restrictive than the property or indexer 'C.T3' // private object T3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T3.get", "C.T3"), // (26,44): error CS0273: The accessibility modifier of the 'C.T4.get' accessor must be more restrictive than the property or indexer 'C.T4' // private object T4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T4.get", "C.T4"), // (273): error CS0273: The accessibility modifier of the 'C.T5.get' accessor must be more restrictive than the property or indexer 'C.T5' // private object T5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T5.get", "C.T5"), // (28,24): error CS0273: The accessibility modifier of the 'C.U1.get' accessor must be more restrictive than the property or indexer 'C.U1' // object U1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U1.get", "C.U1"), // (29,26): error CS0273: The accessibility modifier of the 'C.U2.get' accessor must be more restrictive than the property or indexer 'C.U2' // object U2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U2.get", "C.U2"), // (30,27): error CS0273: The accessibility modifier of the 'C.U3.get' accessor must be more restrictive than the property or indexer 'C.U3' // object U3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U3.get", "C.U3"), // (31,36): error CS0273: The accessibility modifier of the 'C.U4.get' accessor must be more restrictive than the property or indexer 'C.U4' // object U4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U4.get", "C.U4"), // (32,25): error CS0273: The accessibility modifier of the 'C.U5.get' accessor must be more restrictive than the property or indexer 'C.U5' // object U5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U5.get", "C.U5")); } [Fact] public void CS0273ERR_InvalidPropertyAccessMod_Indexers() { var text = @"class C { public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 public object this[int x, double y, int z] { get { return null; } internal set { } } public object this[int x, double y, double z] { get { return null; } protected set { } } public object this[double x, int y, int z] { get { return null; } protected internal set { } } public object this[double x, int y, double z] { get { return null; } private set { } } internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 internal object this[char x, int y, char z] { private get { return null; } set { } } protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected object this[long x, int y, long z] { get { return null; } private set { } } protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 protected internal object this[int x, float y, int z] { get { return null; } internal set { } } protected internal object this[int x, float y, float z] { get { return null; } protected set { } } protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected internal object this[float x, int y, float z] { get { return null; } private set { } } private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 } "; CreateCompilation(text).VerifyDiagnostics( // (3,78): error CS0273: The accessibility modifier of the 'C.this[int, int, double].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, double]' // public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, double].set", "C.this[int, int, double]"), // (8,57): error CS0273: The accessibility modifier of the 'C.this[int, int, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, char]' // internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, char].get", "C.this[int, int, char]"), // (9,59): error CS0273: The accessibility modifier of the 'C.this[int, char, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, int]' // internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, int].get", "C.this[int, char, int]"), // (10,61): error CS0273: The accessibility modifier of the 'C.this[int, char, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, char]' // internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, char].get", "C.this[int, char, char]"), // (11,69): error CS0273: The accessibility modifier of the 'C.this[char, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[char, int, int]' // internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[char, int, int].get", "C.this[char, int, int]"), // (13,79): error CS0273: The accessibility modifier of the 'C.this[int, int, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, long]' // protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, long].set", "C.this[int, int, long]"), // (14,81): error CS0273: The accessibility modifier of the 'C.this[int, long, int].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, int]' // protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, int].set", "C.this[int, long, int]"), // (15,83): error CS0273: The accessibility modifier of the 'C.this[int, long, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, long]' // protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, long].set", "C.this[int, long, long]"), // (16,91): error CS0273: The accessibility modifier of the 'C.this[long, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[long, int, int]' // protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[long, int, int].set", "C.this[long, int, int]"), // (18,89): error CS0273: The accessibility modifier of the 'C.this[int, int, float].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, float]' // protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, float].set", "C.this[int, int, float]"), // (21,101): error CS0273: The accessibility modifier of the 'C.this[float, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[float, int, int]' // protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[float, int, int].set", "C.this[float, int, int]"), // (23,58): error CS0273: The accessibility modifier of the 'C.this[int, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, string]' // private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, string].get", "C.this[int, int, string]"), // (24,60): error CS0273: The accessibility modifier of the 'C.this[int, string, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, int]' // private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, int].get", "C.this[int, string, int]"), // (25,64): error CS0273: The accessibility modifier of the 'C.this[int, string, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, string]' // private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, string].get", "C.this[int, string, string]"), // (26,70): error CS0273: The accessibility modifier of the 'C.this[string, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, int]' // private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, int].get", "C.this[string, int, int]"), // (27,62): error CS0273: The accessibility modifier of the 'C.this[string, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, string]' // private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, string].get", "C.this[string, int, string]"), // (28,50): error CS0273: The accessibility modifier of the 'C.this[int, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, object]' // object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, object].get", "C.this[int, int, object]"), // (29,52): error CS0273: The accessibility modifier of the 'C.this[int, object, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, int]' // object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, int].get", "C.this[int, object, int]"), // (30,56): error CS0273: The accessibility modifier of the 'C.this[int, object, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, object]' // object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, object].get", "C.this[int, object, object]"), // (31,62): error CS0273: The accessibility modifier of the 'C.this[object, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, int]' // object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, int].get", "C.this[object, int, int]"), // (32,54): error CS0273: The accessibility modifier of the 'C.this[object, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, object]' // object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, object].get", "C.this[object, int, object]")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods() { var text = @"class C { public int P { protected get; internal set; } internal object Q { private get { return null; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.P' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P").WithArguments("C.P"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.Q' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "Q").WithArguments("C.Q")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods_Indexer() { var text = @"class C { public int this[int x] { protected get { return 0; } internal set { } } internal object this[object x] { private get { return null; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[int]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[int]"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[object]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[object]")); } [Fact] public void CS0275ERR_PropertyAccessModInInterface() { CreateCompilation( @"interface I { object P { get; } // no error int Q { private get; set; } // CS0275 object R { get; internal set; } // CS0275 } ", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (4,21): error CS8503: The modifier 'private' is not valid for this item in C# 7. Please use language version '8.0' or greater. // int Q { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.0", "8.0").WithLocation(4, 21), // (4,21): error CS0442: 'I.Q.get': abstract properties cannot have private accessors // int Q { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I.Q.get").WithLocation(4, 21), // (5,30): error CS8503: The modifier 'internal' is not valid for this item in C# 7. Please use language version '8.0' or greater. // object R { get; internal set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.0", "8.0").WithLocation(5, 30) ); } [Fact] public void CS0275ERR_PropertyAccessModInInterface_Indexer() { CreateCompilation( @"interface I { object this[int x] { get; } // no error int this[char x] { private get; set; } // CS0275 object this[string x] { get; internal set; } // CS0275 } ", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (4,32): error CS8503: The modifier 'private' is not valid for this item in C# 7. Please use language version '8.0' or greater. // int this[char x] { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.0", "8.0").WithLocation(4, 32), // (4,32): error CS0442: 'I.this[char].get': abstract properties cannot have private accessors // int this[char x] { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I.this[char].get").WithLocation(4, 32), // (5,43): error CS8503: The modifier 'internal' is not valid for this item in C# 7. Please use language version '8.0' or greater. // object this[string x] { get; internal set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.0", "8.0").WithLocation(5, 43) ); } [WorkItem(538620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538620")] [Fact] public void CS0276ERR_AccessModMissingAccessor() { var text = @"class A { public virtual object P { get; protected set; } } class B : A { public override object P { protected set { } } // no error public object Q { private set { } } // CS0276 protected internal object R { internal get { return null; } } // CS0276 } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.Q': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Q").WithArguments("B.Q"), // (9,31): error CS0276: 'B.R': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "R").WithArguments("B.R")); } [Fact] public void CS0276ERR_AccessModMissingAccessor_Indexer() { var text = @"class A { public virtual object this[int x] { get { return null; } protected set { } } } class B : A { public override object this[int x] { protected set { } } // no error public object this[char x] { private set { } } // CS0276 protected internal object this[string x] { internal get { return null; } } // CS0276 } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.this[char]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[char]"), // (9,31): error CS0276: 'B.this[string]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[string]")); } [Fact] public void CS0277ERR_UnimplementedInterfaceAccessor() { var text = @"public interface MyInterface { int Property { get; set; } } public class MyClass : MyInterface // CS0277 { public int Property { get { return 0; } protected set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceAccessor, Line = 10, Column = 24 }); } [Fact(Skip = "530901"), WorkItem(530901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530901")] public void CS0281ERR_FriendRefNotEqualToThis() { //sn -k CS0281.snk //sn -i CS0281.snk CS0281.snk //sn -pc CS0281.snk key.publickey //sn -tp key.publickey //csc /target:library /keyfile:CS0281.snk class1.cs //csc /target:library /keyfile:CS0281.snk /reference:class1.dll class2.cs //csc /target:library /keyfile:CS0281.snk /reference:class2.dll /out:class1.dll program.cs var text1 = @"public class A { }"; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); var text2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Class1 , PublicKey=abc"")] class B : A { } "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); var text3 = @"using System.Runtime.CompilerServices; [assembly: System.Reflection.AssemblyVersion(""3"")] [assembly: System.Reflection.AssemblyCulture(""en-us"")] [assembly: InternalsVisibleTo(""MyServices, PublicKeyToken=aaabbbcccdddeee"")] class C : B { } public class A { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text3, new ErrorDescription { Code = (int)ErrorCode.ERR_FriendRefNotEqualToThis, Line = 10, Column = 14 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0305ERR_BadArity01() { var text = @"namespace NS { interface I<T, V> { } struct S<T> : I<T> { } class C<T> { } public class Test { //public static int Main() //{ // C c = new C(); // Not in Dev10 // return 1; //} I<T, V, U> M<T, V, U>() { return null; } public I<int> field; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 5, Column = 19 }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 13 }, // Dev10 miss this due to other errors //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 23 }, // Dev10 miss this due to other errors new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 17, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 18, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0306ERR_BadTypeArgument01() { var source = @"using System; class C<T> { static void F<U>() { } static void M(object o) { new C<int*>(); new C<ArgIterator>(); new C<RuntimeArgumentHandle>(); new C<TypedReference>(); F<int*>(); o.E<object, ArgIterator>(); Action a; a = F<RuntimeArgumentHandle>; a = o.E<T, TypedReference>; Console.WriteLine(typeof(TypedReference?)); Console.WriteLine(typeof(Nullable<TypedReference>)); } } static class S { internal static void E<T, U>(this object o) { } } "; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (7,15): error CS0306: The type 'int*' may not be used as a type argument // new C<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0306: The type 'ArgIterator' may not be used as a type argument // new C<ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 15), // (9,15): error CS0306: The type 'RuntimeArgumentHandle' may not be used as a type argument // new C<RuntimeArgumentHandle>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(9, 15), // (10,15): error CS0306: The type 'TypedReference' may not be used as a type argument // new C<TypedReference>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(10, 15), // (11,9): error CS0306: The type 'int*' may not be used as a type argument // F<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<int*>").WithArguments("int*").WithLocation(11, 9), // (12,11): error CS0306: The type 'ArgIterator' may not be used as a type argument // o.E<object, ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "E<object, ArgIterator>").WithArguments("System.ArgIterator").WithLocation(12, 11), // (14,13): error CS0306: The type 'RuntimeArgumentHandle' may not be used as a type argument // a = F<RuntimeArgumentHandle>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<RuntimeArgumentHandle>").WithArguments("System.RuntimeArgumentHandle").WithLocation(14, 13), // (15,13): error CS0306: The type 'TypedReference' may not be used as a type argument // a = o.E<T, TypedReference>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "o.E<T, TypedReference>").WithArguments("System.TypedReference").WithLocation(15, 13), // (16,34): error CS0306: The type 'TypedReference' may not be used as a type argument // Console.WriteLine(typeof(TypedReference?)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference?").WithArguments("System.TypedReference").WithLocation(16, 34), // (17,43): error CS0306: The type 'TypedReference' may not be used as a type argument // Console.WriteLine(typeof(Nullable<TypedReference>)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(17, 43)); } /// <summary> /// Bad type arguments for aliases should be reported at the /// alias declaration rather than at the use. (Note: This differs /// from Dev10 which reports errors at the use, with no errors /// reported if there are no uses of the alias.) /// </summary> [Fact] public void CS0306ERR_BadTypeArgument02() { var source = @"using COfObject = C<object>; using COfIntPtr = C<int*>; using COfArgIterator = C<System.ArgIterator>; // unused class C<T> { static void F<U>() { } static void M() { new COfIntPtr(); COfObject.F<int*>(); COfIntPtr.F<object>(); } }"; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (3,7): error CS0306: The type 'ArgIterator' may not be used as a type argument // using COfArgIterator = C<System.ArgIterator>; // unused Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfArgIterator").WithArguments("System.ArgIterator").WithLocation(3, 7), // (2,7): error CS0306: The type 'int*' may not be used as a type argument // using COfIntPtr = C<int*>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfIntPtr").WithArguments("int*").WithLocation(2, 7), // (10,19): error CS0306: The type 'int*' may not be used as a type argument // COfObject.F<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<int*>").WithArguments("int*").WithLocation(10, 19), // (3,1): hidden CS8019: Unnecessary using directive. // using COfArgIterator = C<System.ArgIterator>; // unused Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using COfArgIterator = C<System.ArgIterator>;").WithLocation(3, 1)); } [WorkItem(538157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538157")] [Fact] public void CS0307ERR_TypeArgsNotAllowed() { var text = @"namespace NS { public class Test<T> { internal object field; public int P { get { return 1; } } public static int Main() { Test<int> t = new NS<T>.Test<int>(); var v = t.field<string>; int p = t.P<int>(); if (v == v | p == p | t == t) {} return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,31): error CS0307: The namespace 'NS' cannot be used with type arguments // Test<int> t = new NS<T>.Test<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "NS<T>").WithArguments("NS", "namespace"), // (11,23): error CS0307: The field 'NS.Test<int>.field' cannot be used with type arguments // var v = t.field<string>; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "field<string>").WithArguments("NS.Test<int>.field", "field"), // (12,23): error CS0307: The property 'NS.Test<int>.P' cannot be used with type arguments // int p = t.P<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<int>").WithArguments("NS.Test<int>.P", "property"), // (13,17): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "v == v"), // (13,26): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "p == p"), // (13,35): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (5,25): warning CS0649: Field 'NS.Test<T>.field' is never assigned to, and will always have its default value null // internal object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Test<T>.field", "null") ); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void CS0307ERR_TypeArgsNotAllowed_02() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld<int>); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS0307: The field 'Test.Fld' cannot be used with type arguments // return (int)(Fld<int>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Fld<int>").WithArguments("Test.Fld", "field") ); } [Fact] public void CS0307ERR_TypeArgsNotAllowed_03() { var text = @"class C<T, U> where T : U<T>, new() { static object M() { return new T<U>(); } }"; CreateCompilation(text).VerifyDiagnostics( // (1,25): error CS0307: The type parameter 'U' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "U<T>").WithArguments("U", "type parameter").WithLocation(1, 25), // (5,20): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter").WithLocation(5, 20)); } [Fact] public void CS0308ERR_HasNoTypeVars01() { var text = @"namespace NS { public class Test { public static string F() { return null; } protected void FF(string s) { } public static int Main() { new Test().FF<string, string>(F<int>()); return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 43 }); } [WorkItem(540090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540090")] [Fact] public void CS0308ERR_HasNoTypeVars02() { var text = @" public class NormalType { public static class M2 { public static int F1 = 1; } public static void Test() { int i; i = M2<int>.F1; } public static int Main() { return -1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 8, Column = 13 }); } [Fact] public void CS0400ERR_GlobalSingleTypeNameNotFound01() { var text = @"namespace NS { public class Test { public static int Main() { // global::D d = new global::D(); return 1; } } struct S { global::G field; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,17): error CS0400: The type or namespace name 'G' could not be found in the global namespace (are you missing an assembly reference?) // global::G field; Diagnostic(ErrorCode.ERR_GlobalSingleTypeNameNotFound, "G").WithArguments("G", "<global namespace>"), // (14,19): warning CS0169: The field 'NS.S.field' is never used // global::G field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0405ERR_DuplicateBound() { var source = @"interface IA { } interface IB { } class A { } class B { } class C<T, U> where T : IA, IB, IA where U : A, IA, A { void M<V>() where V : U, IA, U { } }"; CreateCompilation(source).VerifyDiagnostics( // (6,23): error CS0405: Duplicate constraint 'IA' for type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateBound, "IA").WithArguments("IA", "T").WithLocation(6, 23), // (7,22): error CS0405: Duplicate constraint 'A' for type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateBound, "A").WithArguments("A", "U").WithLocation(7, 22), // (9,34): error CS0405: Duplicate constraint 'U' for type parameter 'V' Diagnostic(ErrorCode.ERR_DuplicateBound, "U").WithArguments("U", "V").WithLocation(9, 34)); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } class A { } class B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void CS0409ERR_DuplicateConstraintClause() { var source = @"interface I<T> where T : class where T : struct { void M<U, V>() where U : new() where V : class where U : class where U : I<T>; }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "T").WithArguments("T").WithLocation(3, 11), // (8,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 15), // (9,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(9, 15)); } [Fact] public void CS0415ERR_BadIndexerNameAttr() { var text = @"using System; using System.Runtime.CompilerServices; public interface IA { int this[int index] { get; set; } } public class A : IA { [IndexerName(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } [IndexerName(""Item"")] // CS0415 int P { get; set; } [IndexerName(""Item"")] // CS0592 int f; [IndexerName(""Item"")] // CS0592 void M() { } [IndexerName(""Item"")] // CS0592 event Action E; [IndexerName(""Item"")] // CS0592 class C { } [IndexerName(""Item"")] // CS0592 struct S { } [IndexerName(""Item"")] // CS0592 delegate void D(); } "; CreateCompilation(text).VerifyDiagnostics( // (15,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (22,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (26,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (29,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (32,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (35,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (38,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (41,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (27,9): warning CS0169: The field 'A.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("A.f"), // (33,18): warning CS0067: The event 'A.E' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("A.E")); } [Fact] public void CS0415ERR_BadIndexerNameAttr_Alias() { var text = @" using Alias = System.Runtime.CompilerServices.IndexerNameAttribute; public interface IA { int this[int index] { get; set; } } public class A : IA { [ Alias(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } } "; var compilation = CreateCompilation(text); // NOTE: uses attribute name from syntax. compilation.VerifyDiagnostics( // (11,6): error CS0415: The 'Alias' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, @"Alias").WithArguments("Alias")); // Note: invalid attribute had no effect on metadata name. var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetProperty("IA." + WellKnownMemberNames.Indexer); Assert.Equal("IA.Item", indexer.MetadataName); } [Fact] public void CS0416ERR_AttrArgWithTypeVars() { var text = @"public class MyAttribute : System.Attribute { public MyAttribute(System.Type t) { } } class G<T> { [MyAttribute(typeof(G<T>))] // CS0416 public void F() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttrArgWithTypeVars, Line = 10, Column = 18 }); } [Fact] public void CS0418ERR_AbstractSealedStatic01() { var text = @"namespace NS { public abstract static class C // CS0418 { internal abstract sealed class CC { private static abstract sealed class CCC // CS0418, 0441 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 3, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 5, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 7, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedStaticClass, Line = 7, Column = 50 }); } [Fact] public void CS0423ERR_ComImportWithImpl() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class ImageProperties { public static void Main() // CS0423 { ImageProperties i = new ImageProperties(); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,24): error CS0423: Since 'ImageProperties' has the ComImport attribute, 'ImageProperties.Main()' must be extern or abstract // public static void Main() // CS0423 Diagnostic(ErrorCode.ERR_ComImportWithImpl, "Main").WithArguments("ImageProperties.Main()", "ImageProperties").WithLocation(5, 24)); } [Fact] public void CS0424ERR_ComImportWithBase() { var text = @"using System.Runtime.InteropServices; public class A { } [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B : A { } // CS0424 error "; CreateCompilation(text).VerifyDiagnostics( // (5,7): error CS0424: 'B': a class with the ComImport attribute cannot specify a base class // class B : A { } // CS0424 error Diagnostic(ErrorCode.ERR_ComImportWithBase, "B").WithArguments("B").WithLocation(5, 7)); } [WorkItem(856187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/856187")] [WorkItem(866093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866093")] [Fact] public void CS0424ERR_ComImportWithInitializers() { var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B { public static int X = 5; public int Y = 5; public const decimal D = 5; public const int Yconst = 5; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public static int X = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(7, 25), // (9,28): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public const decimal D = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(9, 28), // (8,18): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public int Y = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(8, 18) ); } [Fact] public void CS0425ERR_ImplBadConstraints01() { var source = @"interface IA<T> { } interface IB { } interface I { // Different constraints: void A1<T>() where T : struct; void A2<T, U>() where T : struct where U : IA<T>; void A3<T>() where T : IA<T>; void A4<T, U>() where T : struct, IA<T>; // Additional constraints: void B1<T>(); void B2<T>() where T : new(); void B3<T, U>() where T : IA<T>; // Missing constraints. void C1<T>() where T : class; void C2<T>() where T : class, new(); void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. void D1<T>() where T : IA<T>, IB; void D2<T, U, V>() where V : T, U; // Different constraint clauses. void E1<T, U>() where U : T; // Additional constraint clause. void F1<T, U>() where T : class; // Missing constraint clause. void G1<T, U>() where T : class where U : T; // Same constraint clauses, different order. void H1<T, U>() where T : class where U : T; void H2<T, U>() where T : class where U : T; void H3<T, U, V>() where V : class where U : IB where T : IA<V>; // Different type parameter names. void K1<T, U>() where T : class where U : T; void K2<T, U>() where T : class where U : T; } class C : I { // Different constraints: public void A1<T>() where T : class { } public void A2<T, U>() where T : struct where U : IB { } public void A3<T>() where T : IA<IA<T>> { } public void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: public void B1<T>() where T : new() { } public void B2<T>() where T : class, new() { } public void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. public void C1<T>() { } public void C2<T>() where T : class { } public void C3<T, U>() where U : IA<T> { } // Same constraints, different order. public void D1<T>() where T : IB, IA<T> { } public void D2<T, U, V>() where V : U, T { } // Different constraint clauses. public void E1<T, U>() where T : class { } // Additional constraint clause. public void F1<T, U>() where T : class where U : T { } // Missing constraint clause. public void G1<T, U>() where T : class { } // Same constraint clauses, different order. public void H1<T, U>() where U : T where T : class { } public void H2<T, U>() where U : class where T : U { } public void H3<T, U, V>() where T : IA<V> where U : IB where V : class { } // Different type parameter names. public void K1<U, T>() where T : class where U : T { } public void K2<T1, T2>() where T1 : class where T2 : T1 { } }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilation(source).VerifyDiagnostics( // (38,17): error CS0425: The constraints for type parameter 'T' of method 'C.A1<T>()' must match the constraints for type parameter 'T' of interface method 'I.A1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A1").WithArguments("T", "C.A1<T>()", "T", "I.A1<T>()").WithLocation(38, 17), // (39,17): error CS0425: The constraints for type parameter 'U' of method 'C.A2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.A2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A2").WithArguments("U", "C.A2<T, U>()", "U", "I.A2<T, U>()").WithLocation(39, 17), // (40,17): error CS0425: The constraints for type parameter 'T' of method 'C.A3<T>()' must match the constraints for type parameter 'T' of interface method 'I.A3<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A3").WithArguments("T", "C.A3<T>()", "T", "I.A3<T>()").WithLocation(40, 17), // (41,17): error CS0425: The constraints for type parameter 'T' of method 'C.A4<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.A4<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A4").WithArguments("T", "C.A4<T, U>()", "T", "I.A4<T, U>()").WithLocation(41, 17), // (43,17): error CS0425: The constraints for type parameter 'T' of method 'C.B1<T>()' must match the constraints for type parameter 'T' of interface method 'I.B1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B1").WithArguments("T", "C.B1<T>()", "T", "I.B1<T>()").WithLocation(43, 17), // (44,17): error CS0425: The constraints for type parameter 'T' of method 'C.B2<T>()' must match the constraints for type parameter 'T' of interface method 'I.B2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B2").WithArguments("T", "C.B2<T>()", "T", "I.B2<T>()").WithLocation(44, 17), // (45,17): error CS0425: The constraints for type parameter 'T' of method 'C.B3<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.B3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B3").WithArguments("T", "C.B3<T, U>()", "T", "I.B3<T, U>()").WithLocation(45, 17), // (47,17): error CS0425: The constraints for type parameter 'T' of method 'C.C1<T>()' must match the constraints for type parameter 'T' of interface method 'I.C1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C1").WithArguments("T", "C.C1<T>()", "T", "I.C1<T>()").WithLocation(47, 17), // (48,17): error CS0425: The constraints for type parameter 'T' of method 'C.C2<T>()' must match the constraints for type parameter 'T' of interface method 'I.C2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C2").WithArguments("T", "C.C2<T>()", "T", "I.C2<T>()").WithLocation(48, 17), // (49,17): error CS0425: The constraints for type parameter 'U' of method 'C.C3<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.C3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C3").WithArguments("U", "C.C3<T, U>()", "U", "I.C3<T, U>()").WithLocation(49, 17), // (54,17): error CS0425: The constraints for type parameter 'T' of method 'C.E1<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("T", "C.E1<T, U>()", "T", "I.E1<T, U>()").WithLocation(54, 17), // (54,17): error CS0425: The constraints for type parameter 'U' of method 'C.E1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("U", "C.E1<T, U>()", "U", "I.E1<T, U>()").WithLocation(54, 17), // (56,17): error CS0425: The constraints for type parameter 'U' of method 'C.F1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.F1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "F1").WithArguments("U", "C.F1<T, U>()", "U", "I.F1<T, U>()").WithLocation(56, 17), // (58,17): error CS0425: The constraints for type parameter 'U' of method 'C.G1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.G1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "G1").WithArguments("U", "C.G1<T, U>()", "U", "I.G1<T, U>()").WithLocation(58, 17), // (61,17): error CS0425: The constraints for type parameter 'T' of method 'C.H2<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("T", "C.H2<T, U>()", "T", "I.H2<T, U>()").WithLocation(61, 17), // (61,17): error CS0425: The constraints for type parameter 'U' of method 'C.H2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("U", "C.H2<T, U>()", "U", "I.H2<T, U>()").WithLocation(61, 17), // (64,17): error CS0425: The constraints for type parameter 'U' of method 'C.K1<U, T>()' must match the constraints for type parameter 'T' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("U", "C.K1<U, T>()", "T", "I.K1<T, U>()").WithLocation(64, 17), // (64,17): error CS0425: The constraints for type parameter 'T' of method 'C.K1<U, T>()' must match the constraints for type parameter 'U' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("T", "C.K1<U, T>()", "U", "I.K1<T, U>()").WithLocation(64, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints02() { var source = @"interface IA<T> { } interface IB { } interface I<T> { void M1<U, V>() where U : T where V : IA<T>; void M2<U>() where U : T, new(); } class C1 : I<IB> { public void M1<U, V>() where U : IB where V : IA<IB> { } public void M2<U>() where U : I<IB> { } } class C2<T, U> : I<IA<U>> { public void M1<X, Y>() where Y : IA<IA<U>> where X : IA<U> { } public void M2<X>() where X : T, new() { } }"; CreateCompilation(source).VerifyDiagnostics( // (11,17): error CS0425: The constraints for type parameter 'U' of method 'C1.M2<U>()' must match the constraints for type parameter 'U' of interface method 'I<IB>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("U", "C1.M2<U>()", "U", "I<IB>.M2<U>()").WithLocation(11, 17), // (16,17): error CS0425: The constraints for type parameter 'X' of method 'C2<T, U>.M2<X>()' must match the constraints for type parameter 'U' of interface method 'I<IA<U>>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("X", "C2<T, U>.M2<X>()", "U", "I<IA<U>>.M2<U>()").WithLocation(16, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints03() { var source = @"interface IA { } class B { } interface I1<T> { void M<U>() where U : struct, T; } class C1<T> : I1<T> where T : struct { public void M<U>() where U : T { } } interface I2<T> { void M<U>() where U : class, T; } class C2 : I2<B> { public void M<U>() where U : B { } } class C2<T> : I2<T> where T : class { public void M<U>() where U : T { } } interface I3<T> { void M<U>() where U : T, new(); } class C3 : I3<B> { public void M<U>() where U : B { } } class C3<T> : I3<T> where T : new() { public void M<U>() where U : T { } } interface I4<T> { void M<U>() where U : T, IA; } class C4 : I4<IA> { public void M<U>() where U : IA { } } class C4<T> : I4<T> where T : IA { public void M<U>() where U : T { } } interface I5<T> { void M<U>() where U : B, T; } class C5 : I5<B> { public void M<U>() where U : B { } } class C5<T> : I5<T> where T : B { public void M<U>() where U : T { } }"; CreateCompilation(source).VerifyDiagnostics( // (9,17): error CS0425: The constraints for type parameter 'U' of method 'C1<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I1<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C1<T>.M<U>()", "U", "I1<T>.M<U>()").WithLocation(9, 17), // (9,19): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 19), // (17,17): error CS0425: The constraints for type parameter 'U' of method 'C2.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2.M<U>()", "U", "I2<B>.M<U>()").WithLocation(17, 17), // (21,17): error CS0425: The constraints for type parameter 'U' of method 'C2<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2<T>.M<U>()", "U", "I2<T>.M<U>()").WithLocation(21, 17), // (29,17): error CS0425: The constraints for type parameter 'U' of method 'C3.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3.M<U>()", "U", "I3<B>.M<U>()").WithLocation(29, 17), // (33,17): error CS0425: The constraints for type parameter 'U' of method 'C3<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3<T>.M<U>()", "U", "I3<T>.M<U>()").WithLocation(33, 17), // (45,17): error CS0425: The constraints for type parameter 'U' of method 'C4<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I4<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C4<T>.M<U>()", "U", "I4<T>.M<U>()").WithLocation(45, 17), // (57,17): error CS0425: The constraints for type parameter 'U' of method 'C5<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I5<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C5<T>.M<U>()", "U", "I5<T>.M<U>()").WithLocation(57, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints04() { var source = @"interface IA { void M1<T>(); void M2<T, U>() where U : T; } interface IB { void M1<T>() where T : IB; void M2<X, Y>(); } abstract class C : IA, IB { public abstract void M1<T>(); public abstract void M2<X, Y>(); }"; CreateCompilation(source).VerifyDiagnostics( // (14,26): error CS0425: The constraints for type parameter 'Y' of method 'C.M2<X, Y>()' must match the constraints for type parameter 'U' of interface method 'IA.M2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("Y", "C.M2<X, Y>()", "U", "IA.M2<T, U>()").WithLocation(14, 26), // (13,26): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "IB.M1<T>()").WithLocation(13, 26)); } [Fact] public void CS0425ERR_ImplBadConstraints05() { var source = @"interface I<T> { } class C { } interface IA<T, U> { void A1<V>() where V : T, I<T>; void A2<V>() where V : T, U, I<T>, I<U>; } interface IB<T> { void B1<U>() where U : C; void B2<U, V>() where U : C, T, V; } class A<T, U> { // More constraints than IA<T, U>.A1<V>(). public void A1<V>() where V : T, U, I<T>, I<U> { } // Fewer constraints than IA<T, U>.A2<V>(). public void A2<V>() where V : T, I<T> { } } class B<T> { // More constraints than IB<T>.B1<U>(). public void B1<U>() where U : C, T { } // Fewer constraints than IB<T>.B2<U, V>(). public void B2<U, V>() where U : T, V { } } class A1<T> : A<T, T>, IA<T, T> { } class A2<T, U> : A<T, U>, IA<T, U> { } class B1 : B<C>, IB<C> { } class B2<T> : B<T>, IB<T> { }"; CreateCompilation(source).VerifyDiagnostics( // (30,27): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A2<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A2<V>()'. Consider using an explicit interface implementation instead. // class A2<T, U> : A<T, U>, IA<T, U> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IA<T, U>").WithArguments("V", "A<T, U>.A2<V>()", "V", "IA<T, U>.A2<V>()").WithLocation(30, 27), // (30,27): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A1<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A1<V>()'. Consider using an explicit interface implementation instead. // class A2<T, U> : A<T, U>, IA<T, U> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IA<T, U>").WithArguments("V", "A<T, U>.A1<V>()", "V", "IA<T, U>.A1<V>()").WithLocation(30, 27), // (36,21): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B2<U, V>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B2<U, V>()'. Consider using an explicit interface implementation instead. // class B2<T> : B<T>, IB<T> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IB<T>").WithArguments("U", "B<T>.B2<U, V>()", "U", "IB<T>.B2<U, V>()").WithLocation(36, 21), // (36,21): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B1<U>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B1<U>()'. Consider using an explicit interface implementation instead. // class B2<T> : B<T>, IB<T> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IB<T>").WithArguments("U", "B<T>.B1<U>()", "U", "IB<T>.B1<U>()").WithLocation(36, 21)); } [Fact] public void CS0425ERR_ImplBadConstraints06() { var source = @"using NIA1 = N.IA; using NIA2 = N.IA; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } class A { } } interface IB { void M1<T>() where T : N.A, N.IA; void M2<T>() where T : NA1, NIA1; } abstract class B1 : IB { public abstract void M1<T>() where T : NA1, NIA1; public abstract void M2<T>() where T : NA2, NIA2; } abstract class B2 : IB { public abstract void M1<T>() where T : NA1; public abstract void M2<T>() where T : NIA2; }"; CreateCompilation(source).VerifyDiagnostics( // (22,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "B2.M1<T>()", "T", "IB.M1<T>()").WithLocation(22, 26), // (23,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M2<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("T", "B2.M2<T>()", "T", "IB.M2<T>()").WithLocation(23, 26)); } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg01() { var text = @"namespace NS { public class C { public interface I { } } struct S { } public class Test { C.I.x field; // CS0426 void M(S.s p) { } // CS0426 public static int Main() { // C.A a; // CS0426 return 1; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,18): error CS0426: The type name 's' does not exist in the type 'NS.S' // void M(S.s p) { } // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "s").WithArguments("s", "NS.S"), // (13,13): error CS0426: The type name 'x' does not exist in the type 'NS.C.I' // C.I.x field; // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "x").WithArguments("x", "NS.C.I"), // (13,15): warning CS0169: The field 'NS.Test.field' is never used // C.I.x field; // CS0426 Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Test.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg02() { var text = @"class A<T> { A<T>.T F = default(A<T>.T); } class B : A<object> { B.T F = default(B.T); }"; CreateCompilation(text).VerifyDiagnostics( // (3,10): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 10), // (3,29): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 29), // (7,7): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 7), // (7,23): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 23)); } [Fact] public void CS0430ERR_BadExternAlias() { var text = @"extern alias MyType; // CS0430 public class Test { public static void Main() {} } public class MyClass { } "; CreateCompilation(text).VerifyDiagnostics( // (1,14): error CS0430: The extern alias 'MyType' was not specified in a /reference option // extern alias MyType; // CS0430 Diagnostic(ErrorCode.ERR_BadExternAlias, "MyType").WithArguments("MyType"), // (1,1): info CS8020: Unused extern alias. // extern alias MyType; // CS0430 Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias MyType;")); } [Fact] public void CS0432ERR_AliasNotFound() { var text = @"class C { public class A { } } class E : C::A { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AliasNotFound, Line = 6, Column = 11 }); } /// <summary> /// Import - same name class from lib1 and lib2 /// </summary> [Fact] public void CS0433ERR_SameFullNameAggAgg01() { var text = @"namespace NS { class Test { Class1 var; void M(Class1 p) {} } } "; var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var ref2 = TestReferences.SymbolsTests.MultiModule.Assembly; // Roslyn give CS0104 for now var comp = CreateCompilation(text, new List<MetadataReference> { ref1, ref2 }); comp.VerifyDiagnostics( // (6,16): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // void M(Class1 p) {} Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,9): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // Class1 var; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,16): warning CS0169: The field 'NS.Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("NS.Test.var")); text = @" class Class1 { } class Test { Class1 var; } "; comp = CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // goo.cs(8,5): warning CS0436: The type 'Class1' in 'goo.cs' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'goo.cs'. // Class1 var; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("goo.cs", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // goo.cs(8,12): warning CS0169: The field 'Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("Test.var") ); } /// <summary> /// import - lib1: namespace A { namespace B { .class C {}.. }} /// vs. lib2: Namespace A { class B { class C{} } }} - use C /// </summary> [Fact] public void CS0434ERR_SameFullNameNsAgg01() { var text = @" namespace NS { public class Test { public static void Main() { // var v = new N1.N2.A(); } void M(N1.N2.A p) { } } } "; var ref1 = TestReferences.DiagnosticTests.ErrTestLib11.dll; var ref2 = TestReferences.DiagnosticTests.ErrTestLib02.dll; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { ref1, ref2 }, // new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 9, Column = 28 }, // Dev10 one error new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 12, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs01() // I (Neal Gafter) was not able to reproduce this in Dev10 using the batch compiler, but the Dev10 // background compiler will emit this diagnostic (along with one other) for this code: // namespace NS { // namespace A { } // public class A { } // } // class B : NS.A { } //Compiling the scenario below using the native compiler gives CS0438 for me (Ed). { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } class Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs03() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs04() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs05() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs06() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0436WRN_SameFullNameThisAggAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util")); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0436WRN_SameFullNameThisAggAgg_02() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0435WRN_SameFullNameThisNsAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0437WRN_SameFullNameThisAggNs_01() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_01() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_03() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (15,15): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_04() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } namespace Util { class A<T> {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }); CompileAndVerify(comp).VerifyDiagnostics(); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_05() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_06() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_07() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_08() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_09() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_10() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_11() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_12() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_13() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_14() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_15() { var mod3Source = @" namespace NS { namespace Util { public class A {} } } "; var mod3Ref = CreateCompilation(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), mod3Ref, s_mod1.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_16() { var mod3Source = @" namespace NS { internal class Util { public class A {} } }"; var mod3Ref = CreateCompilation(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), mod3Ref, s_mod2.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(641639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641639")] public void Bug641639() { var ModuleA01 = @" class A01 { public static int AT = (new { field = 1 }).field; } "; var ModuleA01Ref = CreateCompilation(ModuleA01, options: TestOptions.ReleaseModule, assemblyName: "ModuleA01").EmitToImageReference(); var ModuleB01 = @" class B01{ public static int AT = (new { field = 2 }).field; } "; var ModuleB01Ref = CreateCompilation(ModuleB01, options: TestOptions.ReleaseModule, assemblyName: "ModuleB01").EmitToImageReference(); var text = @" class Test { static void Main() { System.Console.WriteLine(""{0} + {1} = {2}"", A01.AT, A01.AT, B01.AT); A01.AT = B01.AT; System.Console.WriteLine(""{0} = {1}"", A01.AT, B01.AT); } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { ModuleA01Ref, ModuleB01Ref }, TestOptions.ReleaseExe); Assert.Equal(1, comp.Assembly.Modules[1].GlobalNamespace.GetTypeMembers("<ModuleA01>f__AnonymousType0", 1).Length); Assert.Equal(1, comp.Assembly.Modules[2].GlobalNamespace.GetTypeMembers("<ModuleB01>f__AnonymousType0", 1).Length); CompileAndVerify(comp, expectedOutput: @"1 + 1 = 2 2 = 2"); } [Fact] public void NameCollisionWithAddedModule_01() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module ITest20Mod.netmodule // MVID: {53AFCDC2-985A-43AE-928E-89B4A4017344} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00EC0000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ITest20<T> { } // end of class ITest20 "; ImmutableArray<Byte> ilBytes; using (var reference = IlasmUtilities.CreateTempAssembly(ilSource, prependDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var source = @" interface ITest20 {} "; var compilation = CreateCompilation(source, new List<MetadataReference>() { moduleRef }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8004: Type 'ITest20<T>' exported from module 'ITest20Mod.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("ITest20<T>", "ITest20Mod.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_02() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module mod_1_1.netmodule // MVID: {98479031-F5D1-443D-AF73-CF21159C1BCF} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D30000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ns.c1<T> { } .class interface public abstract auto ansi c2<T> { } .class interface public abstract auto ansi ns.C3<T> { } .class interface public abstract auto ansi C4<T> { } .class interface public abstract auto ansi NS1.c5<T> { } "; ImmutableArray<Byte> ilBytes; using (var reference = IlasmUtilities.CreateTempAssembly(ilSource, prependDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef1 = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var mod2Source = @" namespace ns { public interface c1 {} public interface c3 {} } public interface c2 {} public interface c4 {} namespace ns1 { public interface c5 {} } "; var moduleRef2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "mod_1_2").EmitToImageReference(); var compilation = CreateCompilation("", new List<MetadataReference>() { moduleRef1, moduleRef2 }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8005: Type 'c2' exported from module 'mod_1_2.netmodule' conflicts with type 'c2<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("c2", "mod_1_2.netmodule", "c2<T>", "mod_1_1.netmodule"), // error CS8005: Type 'ns.c1' exported from module 'mod_1_2.netmodule' conflicts with type 'ns.c1<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("ns.c1", "mod_1_2.netmodule", "ns.c1<T>", "mod_1_1.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_03() { var forwardedTypesSource = @" public class CF1 {} namespace ns { public class CF2 { } } public class CF3<T> {} "; var forwardedTypes1 = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes1"); var forwardedTypes1Ref = new CSharpCompilationReference(forwardedTypes1); var forwardedTypes2 = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes2"); var forwardedTypes2Ref = new CSharpCompilationReference(forwardedTypes2); var forwardedTypesModRef = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseModule, assemblyName: "forwardedTypesMod"). EmitToImageReference(); var modSource = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(ns.CF2))] "; var module1_FT1_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module1_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module2_FT1_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module2_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module3_FT2_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module3_FT2", references: new MetadataReference[] { forwardedTypes2Ref }). EmitToImageReference(); var module4_Ref = CreateCompilation("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<int>))]", options: TestOptions.ReleaseModule, assemblyName: "module4_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var compilation = CreateCompilation(forwardedTypesSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8006: Forwarded type 'ns.CF2' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("ns.CF2"), // error CS8006: Forwarded type 'CF1' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("CF1")); compilation = CreateCompilation(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); // Exported types in .NET modules cause PEVerify to fail on some platforms. CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<byte>))]", new List<MetadataReference>() { module4_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes2Ref, new CSharpCompilationReference(forwardedTypes1, aliases: ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); compilation = CreateCompilation( @" extern alias FT1; [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::ns.CF2))] ", new List<MetadataReference>() { forwardedTypesModRef, new CSharpCompilationReference(forwardedTypes1, ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule"), // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { forwardedTypesModRef, module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, forwardedTypesModRef, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, module2_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, module3_FT2_Ref, forwardedTypes1Ref, forwardedTypes2Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void CS0441ERR_SealedStaticClass01() { var text = @"namespace NS { static sealed class Test { public static int Main() { return 1; } } sealed static class StaticClass : Test //verify 'sealed' works { } static class Derived : StaticClass //verify 'sealed' works { // Test tst = new Test(); //verify 'static' works } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,25): error CS0441: 'NS.Test': a type cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "Test").WithArguments("NS.Test"), // (11,25): error CS0441: 'NS.StaticClass': a type cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "StaticClass").WithArguments("NS.StaticClass"), //CONSIDER: Dev10 skips these cascading errors // (11,39): error CS07: Static class 'NS.StaticClass' cannot derive from type 'NS.Test'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Test").WithArguments("NS.StaticClass", "NS.Test"), // (15,28): error CS07: Static class 'NS.Derived' cannot derive from type 'NS.StaticClass'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "StaticClass").WithArguments("NS.Derived", "NS.StaticClass")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0442ERR_PrivateAbstractAccessor() { var source = @"abstract class MyClass { public abstract int P { get; private set; } // CS0442 protected abstract object Q { private get; set; } // CS0442 internal virtual object R { private get; set; } // no error } "; CreateCompilation(source).VerifyDiagnostics( // (3,42): error CS0442: 'MyClass.P.set': abstract properties cannot have private accessors // public abstract int P { get; private set; } // CS0442 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "set").WithArguments("MyClass.P.set").WithLocation(3, 42), // (4,43): error CS0442: 'MyClass.Q.get': abstract properties cannot have private accessors // protected abstract object Q { private get; set; } // CS0442 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("MyClass.Q.get").WithLocation(4, 43)); } [Fact] public void CS0448ERR_BadIncDecRetType() { // Note that the wording of this error message has changed slightly from the native compiler. var text = @"public struct S { public static S? operator ++(S s) { return new S(); } // CS0448 public static S? operator --(S s) { return new S(); } // CS0448 }"; CreateCompilation(text).VerifyDiagnostics( // (3,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator ++(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "++"), // (4,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator --(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "--")); } [Fact] public void CS0450ERR_RefValBoundWithClass() { var source = @"interface I { } class A { } class B<T> { } class C<T1, T2, T3, T4, T5, T6, T7> where T1 : class, I where T2 : struct, I where T3 : class, A where T4 : struct, B<T5> where T6 : class, T5 where T7 : struct, T5 { }"; CreateCompilation(source).VerifyDiagnostics( // (7,23): error CS0450: 'A': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "A").WithArguments("A").WithLocation(7, 23), // (8, 24): error CS0450: 'B<T5>': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "B<T5>").WithArguments("B<T5>").WithLocation(8, 24)); } [Fact] public void CS0452ERR_RefConstraintNotSatisfied() { var source = @"interface I { } class A { } class B<T> where T : class { } class C { static void F<U>() where U : class { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>() Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (19,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(19, 15), // (20,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(20, 9), // (24,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (39,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied01() { var source = @"interface I { } class A { } class B<T> where T : struct { } class C { static void F<U>() where U : struct { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (14,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(14, 15), // (15,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(15, 9), // (24,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (34,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(34, 15), // (35,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(35, 9), // (39,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied02() { var source = @"abstract class A<X, Y> { internal static void F<U>() where U : struct { } internal abstract void M<U>() where U : X, Y; } class B1 : A<int?, object> { internal override void M<U>() { F<U>(); } } class B2 : A<object, int?> { internal override void M<U>() { F<U>(); } } class B3 : A<object, int> { internal override void M<U>() { F<U>(); } } class B4<T> : A<object, T> { internal override void M<U>() { F<U>(); } } class B5<T> : A<object, T> where T : struct { internal override void M<U>() { F<U>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<int?, object>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<int?, object>.F<U>()", "U", "U").WithLocation(10, 9), // (17,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, int?>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, int?>.F<U>()", "U", "U").WithLocation(17, 9), // (31,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, T>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, T>.F<U>()", "U", "U").WithLocation(31, 9)); } [Fact] public void CS0454ERR_CircularConstraint01() { var source = @"class A<T> where T : T { } class B<T, U, V> where V : T where U : V where T : U { } delegate void D<T1, T2, T3>() where T1 : T3 where T2 : T2 where T3 : T1;"; CreateCompilation(source).VerifyDiagnostics( // (1,9): error CS0454: Circular constraint dependency involving 'T' and 'T' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(1, 9), // (4,9): error CS0454: Circular constraint dependency involving 'T' and 'V' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "V").WithLocation(4, 9), // (10,17): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(10, 17), // (10,21): error CS0454: Circular constraint dependency involving 'T2' and 'T2' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T2").WithLocation(10, 21)); } [Fact] public void CS0454ERR_CircularConstraint02() { var source = @"interface I { void M<T, U, V>() where T : V, new() where U : class, V where V : U; } class A<T> { } class B<T, U> where T : U where U : A<U>, U { }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0454: Circular constraint dependency involving 'V' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "V").WithArguments("V", "U").WithLocation(3, 18), // (9,12): error CS0454: Circular constraint dependency involving 'U' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(9, 12)); } [Fact] public void CS0454ERR_CircularConstraint03() { var source = @"interface I<T1, T2, T3, T4, T5> where T1 : T2, T4 where T2 : T3 where T3 : T1 where T4 : T5 where T5 : T1 { } class C<T1, T2, T3, T4, T5> where T1 : T2, T3 where T2 : T3, T4 where T3 : T4, T5 where T5 : T2, T3 { } struct S<T1, T2, T3, T4, T5> where T4 : T1 where T5 : T2 where T1 : T3 where T2 : T4 where T3 : T5 { } delegate void D<T1, T2, T3, T4>() where T1 : T2 where T2 : T3, T4 where T3 : T4 where T4 : T2;"; CreateCompilation(source).VerifyDiagnostics( // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(1, 13), // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T5").WithLocation(1, 13), // (9,13): error CS0454: Circular constraint dependency involving 'T2' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T5").WithLocation(9, 13), // (9,17): error CS0454: Circular constraint dependency involving 'T3' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T3").WithArguments("T3", "T5").WithLocation(9, 17), // (16,10): error CS0454: Circular constraint dependency involving 'T1' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T4").WithLocation(16, 10), // (24,21): error CS0454: Circular constraint dependency involving 'T2' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T4").WithLocation(24, 21)); } [Fact] public void CS0454ERR_CircularConstraint04() { var source = @"interface I<T> where U : U { } class C<T, U> where T : U where U : class where U : T { }"; CreateCompilation(source).VerifyDiagnostics( // (2,11): error CS0699: 'I<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "I<T>").WithLocation(2, 11), // (8,11): error CS0409: A constraint clause has already been specified for type parameter 'U'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 11)); } [Fact] public void CS0455ERR_BaseConstraintConflict01() { var source = @"class A<T> { } class B : A<int> { } class C<T, U> where T : B, U where U : A<int> { } class D<T, U> where T : A<T> where U : B, T { }"; CreateCompilation(source).VerifyDiagnostics( // (8,12): error CS0455: Type parameter 'U' inherits conflicting constraints 'A<T>' and 'B' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "A<T>", "B").WithLocation(8, 12)); } [Fact] public void CS0455ERR_BaseConstraintConflict02() { var source = @"class A<T> { internal virtual void M1<U>() where U : struct, T { } internal virtual void M2<U>() where U : class, T { } } class B1 : A<object> { internal override void M1<U>() { } internal override void M2<U>() { } } class B2 : A<int> { internal override void M1<U>() { } internal override void M2<U>() { } } class B3 : A<string> { internal override void M1<U>() { } internal override void M2<U>() { } } class B4 : A<int?> { internal override void M1<T>() { } internal override void M2<X>() { } }"; CreateCompilation(source).VerifyDiagnostics( // (14,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'int' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "int", "class").WithLocation(14, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'string' and 'System.ValueType' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "string", "System.ValueType").WithLocation(18, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'System.ValueType' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "System.ValueType", "struct").WithLocation(18, 31), // (23,31): error CS0455: Type parameter 'T' inherits conflicting constraints 'int?' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "T").WithArguments("T", "int?", "struct").WithLocation(23, 31), // (24,31): error CS0455: Type parameter 'X' inherits conflicting constraints 'int?' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "X").WithArguments("X", "int?", "class").WithLocation(24, 31)); } [Fact] public void CS0456ERR_ConWithValCon() { var source = @"class A<T, U> where T : struct where U : T { } class B<T> where T : struct { void M<U>() where U : T { } struct S<U> where U : T { } }"; CreateCompilation(source).VerifyDiagnostics( // (1,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(1, 12), // (8,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(8, 12), // (9,14): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 14)); } [Fact] public void CS0462ERR_AmbigOverride() { var text = @"class C<T> { public virtual void F(T t) {} public virtual void F(int t) {} } class D : C<int> { public override void F(int t) {} // CS0462 } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation) { comp.VerifyDiagnostics( // (9,25): error CS0462: The inherited members 'C<T>.F(T)' and 'C<T>.F(int)' have the same signature in type 'D', so they cannot be overridden // public override void F(int t) {} // CS0462 Diagnostic(ErrorCode.ERR_AmbigOverride, "F").WithArguments("C<T>.F(T)", "C<T>.F(int)", "D").WithLocation(9, 25) ); } else { comp.VerifyDiagnostics( // (3,24): warning CS1957: Member 'D.F(int)' overrides 'C<int>.F(int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void F(T t) {} Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F").WithArguments("C<int>.F(int)", "D.F(int)").WithLocation(3, 24), // (9,25): error CS0462: The inherited members 'C<T>.F(T)' and 'C<T>.F(int)' have the same signature in type 'D', so they cannot be overridden // public override void F(int t) {} // CS0462 Diagnostic(ErrorCode.ERR_AmbigOverride, "F").WithArguments("C<T>.F(T)", "C<T>.F(int)", "D").WithLocation(9, 25) ); } } [Fact] public void CS0466ERR_ExplicitImplParams() { var text = @"interface I { void M1(params int[] a); void M2(int[] a); } class C1 : I { //implicit implementations can add or remove 'params' public virtual void M1(int[] a) { } public virtual void M2(params int[] a) { } } class C2 : I { //explicit implementations can remove but not add 'params' void I.M1(int[] a) { } void I.M2(params int[] a) { } //CS0466 } class C3 : C1 { //overrides can add or remove 'params' public override void M1(params int[] a) { } public override void M2(int[] a) { } } class C4 : C1 { //hiding methods can add or remove 'params' public new void M1(params int[] a) { } public new void M2(int[] a) { } } "; CreateCompilation(text).VerifyDiagnostics( // (18,12): error CS0466: 'C2.I.M2(params int[])' should not have a params parameter since 'I.M2(int[])' does not Diagnostic(ErrorCode.ERR_ExplicitImplParams, "M2").WithArguments("C2.I.M2(params int[])", "I.M2(int[])")); } [Fact] public void CS0470ERR_MethodImplementingAccessor() { var text = @"interface I { int P { get; } } class MyClass : I { public int get_P() { return 0; } // CS0470 public int P2 { get { return 0; } } // OK } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 17 }, //Dev10 doesn't include this new ErrorDescription { Code = (int)ErrorCode.ERR_MethodImplementingAccessor, Line = 8, Column = 16 }); } [Fact] public void CS0500ERR_AbstractHasBody01() { var text = @"namespace NS { abstract public class clx { abstract public void M1() { } internal abstract object M2() { return null; } protected abstract internal void M3(sbyte p) { } public abstract object P { get { return null; } set { } } public abstract event System.Action E { add { } remove { } } public abstract event System.Action X { add => throw null; remove => throw null; } } // class clx } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (5,30): error CS0500: 'clx.M1()' cannot declare a body because it is marked abstract // abstract public void M1() { } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("NS.clx.M1()").WithLocation(5, 30), // (6,34): error CS0500: 'clx.M2()' cannot declare a body because it is marked abstract // internal abstract object M2() { return null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M2").WithArguments("NS.clx.M2()").WithLocation(6, 34), // (7,42): error CS0500: 'clx.M3(sbyte)' cannot declare a body because it is marked abstract // protected abstract internal void M3(sbyte p) { } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M3").WithArguments("NS.clx.M3(sbyte)").WithLocation(7, 42), // (8,36): error CS0500: 'clx.P.get' cannot declare a body because it is marked abstract // public abstract object P { get { return null; } set { } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("NS.clx.P.get").WithLocation(8, 36), // (8,57): error CS0500: 'clx.P.set' cannot declare a body because it is marked abstract // public abstract object P { get { return null; } set { } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("NS.clx.P.set").WithLocation(8, 57), // (9,47): error CS8712: 'clx.E': abstract event cannot use event accessor syntax // public abstract event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("NS.clx.E").WithLocation(9, 47), // (10,47): error CS8712: 'clx.X': abstract event cannot use event accessor syntax // public abstract event System.Action X { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("NS.clx.X").WithLocation(10, 47)); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0501ERR_ConcreteMissingBody01() { var text = @" namespace NS { public class clx<T> { public void M1(T t); internal V M2<V>(); protected internal void M3(sbyte p); public static int operator+(clx<T> c); } // class clx } "; CreateCompilation(text).VerifyDiagnostics( // (7,21): error CS0501: 'NS.clx<T>.M1(T)' must declare a body because it is not marked abstract, extern, or partial // public void M1(T t); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("NS.clx<T>.M1(T)"), // (8,20): error CS0501: 'NS.clx<T>.M2<V>()' must declare a body because it is not marked abstract, extern, or partial // internal V M2<V>(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M2").WithArguments("NS.clx<T>.M2<V>()"), // (9,33): error CS0501: 'NS.clx<T>.M3(sbyte)' must declare a body because it is not marked abstract, extern, or partial // protected internal void M3(sbyte p); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M3").WithArguments("NS.clx<T>.M3(sbyte)"), // (10,35): error CS0501: 'NS.clx<T>.operator +(NS.clx<T>)' must declare a body because it is not marked abstract, extern, or partial // public static int operator+(clx<T> c); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("NS.clx<T>.operator +(NS.clx<T>)")); } [Fact] public void CS0501ERR_ConcreteMissingBody02() { var text = @"abstract class C { public int P { get; set { } } public int Q { get { return 0; } set; } public extern object R { get; } // no error protected abstract object S { set; } // no error } "; CreateCompilation(text).VerifyDiagnostics( // (3,20): error CS0501: 'C.P.get' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C.P.get"), // (4,38): error CS0501: 'C.Q.set' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C.Q.set"), // (5,30): warning CS0626: Method, operator, or accessor 'C.R.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.R.get")); } [Fact] public void CS0501ERR_ConcreteMissingBody03() { var source = @"class C { public C(); internal abstract C(C c); extern public C(object o); // no error }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()"), // (4,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,19): warning CS0824: Constructor 'C.C(object)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("C.C(object)")); } [Fact] public void CS0502ERR_AbstractAndSealed01() { var text = @"namespace NS { abstract public class clx { abstract public void M1(); abstract protected void M2<T>(T t); internal abstract object P { get; } abstract public event System.Action E; } // class clx abstract public class cly : clx { abstract sealed override public void M1(); abstract sealed override protected void M2<T>(T t); internal abstract sealed override object P { get; } public abstract sealed override event System.Action E; } // class cly } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 13, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 14, Column = 49 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 15, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 16, Column = 61 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0503ERR_AbstractNotVirtual01() { var source = @"namespace NS { abstract public class clx { abstract virtual internal void M1(); abstract virtual protected void M2<T>(T t); virtual abstract public object P { get; set; } virtual abstract public event System.Action E; } // class clx } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (7,40): error CS0503: The abstract property 'clx.P' cannot be marked virtual // virtual abstract public object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P").WithArguments("property", "NS.clx.P").WithLocation(7, 40), // (6,41): error CS0503: The abstract method 'clx.M2<T>(T)' cannot be marked virtual // abstract virtual protected void M2<T>(T t); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M2").WithArguments("method", "NS.clx.M2<T>(T)").WithLocation(6, 41), // (5,40): error CS0503: The abstract method 'clx.M1()' cannot be marked virtual // abstract virtual internal void M1(); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M1").WithArguments("method", "NS.clx.M1()").WithLocation(5, 40), // (8,53): error CS0503: The abstract event 'clx.E' cannot be marked virtual // virtual abstract public event System.Action E; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "E").WithArguments("event", "NS.clx.E").WithLocation(8, 53)); var nsNamespace = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var clxClass = nsNamespace.GetMembers("clx").Single() as NamedTypeSymbol; Assert.Equal(9, clxClass.GetMembers().Length); } [Fact] public void CS0504ERR_StaticConstant() { var text = @"namespace x { abstract public class clx { static const int i = 0; // CS0504, cannot be both static and const abstract public void f(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstant, Line = 5, Column = 26 }); } [Fact] public void CS0505ERR_CantOverrideNonFunction() { var text = @"public class clx { public int i; } public class cly : clx { public override int i() { return 0; } // CS0505 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonFunction, Line = 8, Column = 24 }); } [Fact] public void CS0506ERR_CantOverrideNonVirtual() { var text = @"namespace MyNameSpace { abstract public class ClassX { public int f() { return 0; } } public class ClassY : ClassX { public override int f() // CS0506 { return 0; } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 13, Column = 29 }); } private const string s_typeWithMixedProperty = @" .class public auto ansi beforefieldinit Base_VirtGet_Set extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_VirtGet_Set::get_Prop() .set instance void Base_VirtGet_Set::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit Base_Get_VirtSet extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname newslot virtual instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_Get_VirtSet::get_Prop() .set instance void Base_Get_VirtSet::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } "; [WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } "; var comp = CreateCompilationWithILAndMscorlib40(text, s_typeWithMixedProperty); comp.VerifyDiagnostics( // (4,25): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // get { return base.Prop; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "get").WithArguments("Derived1.Prop.get", "Base_Get_VirtSet.Prop.get"), // (16,9): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // set { base.Prop = value; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "set").WithArguments("Derived2.Prop.set", "Base_VirtGet_Set.Prop.set")); } [WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported_NO_ERROR() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } } } "; var comp = CreateCompilationWithILAndMscorlib40(text, s_typeWithMixedProperty); comp.VerifyDiagnostics(); } [WorkItem(539586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539586")] [Fact] public void CS0506ERR_CantOverrideNonVirtual02() { var text = @"public class BaseClass { public virtual int Test() { return 1; } } public class BaseClass2 : BaseClass { public static int Test() // Warning CS0114 { return 1; } } public class MyClass : BaseClass2 { public override int Test() // Error CS0506 { return 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 19, Column = 25 }); } [Fact] public void CS0507ERR_CantChangeAccessOnOverride() { var text = @"abstract public class clx { virtual protected void f() { } } public class cly : clx { public override void f() { } // CS0507 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 8, Column = 26 }); } [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride() { var text = @"abstract public class Clx { public int i = 0; abstract public int F(); } public class Cly : Clx { public override double F() { return 0.0; // CS0508 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 9, Column = 28 }); } [WorkItem(540325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540325")] [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride2() { // When the overriding and overridden methods differ in their generic method // type parameter names, the error message should state what the return type // type should be on the overriding method using its type parameter names, // rather than using the return type of the overridden method. var text = @" class G { internal virtual T GM<T>(T t) { return t; } } class GG : G { internal override void GM<V>(V v) { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS0508: 'GG.GM<V>(V)': return type must be 'V' to match overridden member 'G.GM<T>(T)' // internal override void GM<V>(V v) { } Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GM").WithArguments("GG.GM<V>(V)", "G.GM<T>(T)", "V") ); } [Fact] public void CS0509ERR_CantDeriveFromSealedType01() { var source = @"namespace NS { public struct stx { } public sealed class clx {} public class cly : clx {} public class clz : stx { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS0509: 'clz': cannot derive from sealed type 'stx' // public class clz : stx { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "stx").WithArguments("NS.clz", "NS.stx").WithLocation(7, 24), // (6,24): error CS0509: 'cly': cannot derive from sealed type 'clx' // public class cly : clx {} Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "clx").WithArguments("NS.cly", "NS.clx").WithLocation(6, 24)); } [Fact] public void CS0509ERR_CantDeriveFromSealedType02() { var source = @"namespace N1 { enum E { A, B } } namespace N2 { class C : N1.E { } class D : System.Int32 { } class E : int { } } "; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0509: 'E': cannot derive from sealed type 'int' // class E : int { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "int").WithArguments("N2.E", "int").WithLocation(6, 15), // (4,15): error CS0509: 'C': cannot derive from sealed type 'E' // class C : N1.E { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "N1.E").WithArguments("N2.C", "N1.E").WithLocation(4, 15), // (5,15): error CS0509: 'D': cannot derive from sealed type 'int' // class D : System.Int32 { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "System.Int32").WithArguments("N2.D", "int").WithLocation(5, 15)); } [Fact] public void CS0513ERR_AbstractInConcreteClass01() { var source = @"namespace NS { public class clx { abstract public void M1(); internal abstract object M2(); protected abstract internal void M3(sbyte p); public abstract object P { get; set; } } } "; CreateCompilation(source).VerifyDiagnostics( // (8,36): error CS0513: 'clx.P.get' is abstract but it is contained in non-abstract type 'clx' // public abstract object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("NS.clx.P.get", "NS.clx").WithLocation(8, 36), // (8,41): error CS0513: 'clx.P.set' is abstract but it is contained in non-abstract type 'clx' // public abstract object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("NS.clx.P.set", "NS.clx").WithLocation(8, 41), // (6,34): error CS0513: 'clx.M2()' is abstract but it is contained in non-abstract type 'clx' // internal abstract object M2(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M2").WithArguments("NS.clx.M2()", "NS.clx").WithLocation(6, 34), // (7,42): error CS0513: 'clx.M3(sbyte)' is abstract but it is contained in non-abstract type 'clx' // protected abstract internal void M3(sbyte p); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M3").WithArguments("NS.clx.M3(sbyte)", "NS.clx").WithLocation(7, 42), // (5,30): error CS0513: 'clx.M1()' is abstract but it is contained in non-abstract type 'clx' // abstract public void M1(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M1").WithArguments("NS.clx.M1()", "NS.clx").WithLocation(5, 30)); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" class C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void CS0515ERR_StaticConstructorWithAccessModifiers01() { var text = @"namespace NS { static public class clx { private static clx() { } class C<T, V> { internal static C() { } } } public class clz { public static clz() { } struct S { internal static S() { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 5, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 9, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 15, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 19, Column = 29 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Some - /nostdlib - no mscorlib /// </summary> [Fact] public void CS0518ERR_PredefinedTypeNotFound01() { var text = @"namespace NS { class Test { static int Main() { return 1; } } } "; CreateEmptyCompilation(text).VerifyDiagnostics( // (3,11): error CS0518: Predefined type 'System.Object' is not defined or imported // class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object"), // (5,16): error CS0518: Predefined type 'System.Int32' is not defined or imported // static int Main() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32"), // (7,20): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32"), // (3,11): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0")); } //[Fact(Skip = "Bad test case")] //public void CS0520ERR_PredefinedTypeBadType() //{ // var text = @""; // var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription { Code = (int)ErrorCode.ERR_PredefinedTypeBadType, Line = 5, Column = 26 } // ); //} [Fact] public void CS0523ERR_StructLayoutCycle01() { var text = @"struct A { A F; // CS0523 } struct B { C F; // CS0523 C G; // no additional error } struct C { B G; // CS0523 } struct D<T> { D<D<object>> F; // CS0523 } struct E { F<E> F; // no error } class F<T> { E G; // no error } struct G { H<G> F; // CS0523 } struct H<T> { G G; // CS0523 } struct J { static J F; // no error } struct K { static L F; // no error } struct L { static K G; // no error } "; CreateCompilation(text).VerifyDiagnostics( // (7,7): error CS0523: Struct member 'B.F' of type 'C' causes a cycle in the struct layout // C F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("B.F", "C").WithLocation(7, 7), // (12,7): error CS0523: Struct member 'C.G' of type 'B' causes a cycle in the struct layout // B G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("C.G", "B").WithLocation(12, 7), // (16,18): error CS0523: Struct member 'D<T>.F' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("D<T>.F", "D<D<object>>").WithLocation(16, 18), // (32,7): error CS0523: Struct member 'H<T>.G' of type 'G' causes a cycle in the struct layout // G G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("H<T>.G", "G").WithLocation(32, 7), // (28,10): error CS0523: Struct member 'G.F' of type 'H<G>' causes a cycle in the struct layout // H<G> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("G.F", "H<G>").WithLocation(28, 10), // (3,7): error CS0523: Struct member 'A.F' of type 'A' causes a cycle in the struct layout // A F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("A.F", "A").WithLocation(3, 7), // (16,18): warning CS0169: The field 'D<T>.F' is never used // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("D<T>.F").WithLocation(16, 18), // (32,7): warning CS0169: The field 'H<T>.G' is never used // G G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("H<T>.G").WithLocation(32, 7), // (12,7): warning CS0169: The field 'C.G' is never used // B G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("C.G").WithLocation(12, 7), // (40,14): warning CS0169: The field 'K.F' is never used // static L F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("K.F").WithLocation(40, 14), // (28,10): warning CS0169: The field 'G.F' is never used // H<G> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("G.F").WithLocation(28, 10), // (8,7): warning CS0169: The field 'B.G' is never used // C G; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(8, 7), // (36,14): warning CS0169: The field 'J.F' is never used // static J F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("J.F").WithLocation(36, 14), // (3,7): warning CS0169: The field 'A.F' is never used // A F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (20,10): warning CS0169: The field 'E.F' is never used // F<E> F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("E.F").WithLocation(20, 10), // (44,14): warning CS0169: The field 'L.G' is never used // static K G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("L.G").WithLocation(44, 14), // (7,7): warning CS0169: The field 'B.F' is never used // C F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F").WithLocation(7, 7), // (24,7): warning CS0169: The field 'F<T>.G' is never used // E G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("F<T>.G").WithLocation(24, 7) ); } [Fact] public void CS0523ERR_StructLayoutCycle02() { var text = @"struct A { A P { get; set; } // CS0523 A Q { get; set; } // no additional error } struct B { C P { get; set; } // CS0523 (no error in Dev10!) } struct C { B Q { get; set; } // CS0523 (no error in Dev10!) } struct D<T> { D<D<object>> P { get; set; } // CS0523 } struct E { F<E> P { get; set; } // no error } class F<T> { E Q { get; set; } // no error } struct G { H<G> P { get; set; } // CS0523 G Q; // no additional error } struct H<T> { G Q; // CS0523 } struct J { static J P { get; set; } // no error } struct K { static L P { get; set; } // no error } struct L { static K Q { get; set; } // no error } struct M { N P { get; set; } // no error } struct N { M Q // no error { get { return new M(); } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,7): error CS0523: Struct member 'A.P' of type 'A' causes a cycle in the struct layout // A P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("A.P", "A"), // (8,7): error CS0523: Struct member 'B.P' of type 'C' causes a cycle in the struct layout // C P { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("B.P", "C"), // (12,7): error CS0523: Struct member 'C.Q' of type 'B' causes a cycle in the struct layout // B Q { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("C.Q", "B"), // (16,18): error CS0523: Struct member 'D<T>.P' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("D<T>.P", "D<D<object>>"), // (28,10): error CS0523: Struct member 'G.P' of type 'H<G>' causes a cycle in the struct layout // H<G> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("G.P", "H<G>"), // (33,7): error CS0523: Struct member 'H<T>.Q' of type 'G' causes a cycle in the struct layout // G Q; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("H<T>.Q", "G"), // (29,7): warning CS0169: The field 'G.Q' is never used // G Q; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("G.Q"), // (33,7): warning CS0169: The field 'H<T>.Q' is never used // G Q; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("H<T>.Q") ); } [WorkItem(540215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540215")] [Fact] public void CS0523ERR_StructLayoutCycle03() { // Static fields should not be considered when // determining struct cycles. (Note: Dev10 does // report these cases as errors though.) var text = @"struct A { B F; // no error } struct B { static A G; // no error } "; CreateCompilation(text).VerifyDiagnostics( // (3,7): warning CS0169: The field 'A.F' is never used // B F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (7,14): warning CS0169: The field 'B.G' is never used // static A G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(7, 14) ); } [WorkItem(541629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541629")] [Fact] public void CS0523ERR_StructLayoutCycle04() { var text = @"struct E { } struct X<T> { public T t; } struct Y { public X<Z> xz; } struct Z { public X<E> xe; public X<Y> xy; } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0523: Struct member 'Y.xz' of type 'X<Z>' causes a cycle in the struct layout // public X<Z> xz; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xz").WithArguments("Y.xz", "X<Z>").WithLocation(9, 17), // (14,17): error CS0523: Struct member 'Z.xy' of type 'X<Y>' causes a cycle in the struct layout // public X<Y> xy; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xy").WithArguments("Z.xy", "X<Y>").WithLocation(14, 17), // (9,17): warning CS0649: Field 'Y.xz' is never assigned to, and will always have its default value // public X<Z> xz; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xz").WithArguments("Y.xz", "").WithLocation(9, 17), // (14,17): warning CS0649: Field 'Z.xy' is never assigned to, and will always have its default value // public X<Y> xy; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xy").WithArguments("Z.xy", "").WithLocation(14, 17), // (5,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", "").WithLocation(5, 14), // (13,17): warning CS0649: Field 'Z.xe' is never assigned to, and will always have its default value // public X<E> xe; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xe").WithArguments("Z.xe", "").WithLocation(13, 17) ); } [WorkItem(541629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541629")] [Fact] public void CS0523ERR_StructLayoutCycle05() { var text = @"struct X<T> { public T t; } struct W<T> { X<W<W<T>>> x; }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): error CS0523: Struct member 'W<T>.x' of type 'X<W<W<T>>>' causes a cycle in the struct layout // X<W<W<T>>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("W<T>.x", "X<W<W<T>>>"), // (3,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", ""), // (8,16): warning CS0169: The field 'W<T>.x' is never used // X<W<W<T>>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("W<T>.x") ); } [Fact] public void CS0523ERR_StructLayoutCycle06() { var text = @"struct S1<T, U> { S1<object, object> F; } struct S2<T, U> { S2<U, T> F; } struct S3<T> { T F; } struct S4<T> { S3<S3<T>> F; }"; CreateCompilation(text).VerifyDiagnostics( // (3,24): error CS0523: Struct member 'S1<T, U>.F' of type 'S1<object, object>' causes a cycle in the struct layout // S1<object, object> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S1<T, U>.F", "S1<object, object>").WithLocation(3, 24), // (7,14): error CS0523: Struct member 'S2<T, U>.F' of type 'S2<U, T>' causes a cycle in the struct layout // S2<U, T> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S2<T, U>.F", "S2<U, T>").WithLocation(7, 14), // (7,14): warning CS0169: The field 'S2<T, U>.F' is never used // S2<U, T> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S2<T, U>.F").WithLocation(7, 14), // (11,7): warning CS0169: The field 'S3<T>.F' is never used // T F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S3<T>.F").WithLocation(11, 7), // (15,15): warning CS0169: The field 'S4<T>.F' is never used // S3<S3<T>> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S4<T>.F").WithLocation(15, 15), // (3,24): warning CS0169: The field 'S1<T, U>.F' is never used // S1<object, object> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S1<T, U>.F").WithLocation(3, 24) ); } [WorkItem(872954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872954")] [Fact] public void CS0523ERR_StructLayoutCycle07() { var text = @"struct S0<T> { static S0<T> x; } struct S1<T> { class C { } static S1<C> x; } struct S2<T> { struct S { } static S2<S> x; } struct S3<T> { interface I { } static S3<I> x; } struct S4<T> { delegate void D(); static S4<D> x; } struct S5<T> { enum E { } static S5<E> x; } struct S6<T> { static S6<T[]> x; }"; CreateCompilation(text).VerifyDiagnostics( // (8,18): error CS0523: Struct member 'S1<T>.x' of type 'S1<S1<T>.C>' causes a cycle in the struct layout // static S1<C> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S1<T>.x", "S1<S1<T>.C>").WithLocation(8, 18), // (13,18): error CS0523: Struct member 'S2<T>.x' of type 'S2<S2<T>.S>' causes a cycle in the struct layout // static S2<S> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S2<T>.x", "S2<S2<T>.S>").WithLocation(13, 18), // (18,18): error CS0523: Struct member 'S3<T>.x' of type 'S3<S3<T>.I>' causes a cycle in the struct layout // static S3<I> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S3<T>.x", "S3<S3<T>.I>").WithLocation(18, 18), // (23,18): error CS0523: Struct member 'S4<T>.x' of type 'S4<S4<T>.D>' causes a cycle in the struct layout // static S4<D> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S4<T>.x", "S4<S4<T>.D>").WithLocation(23, 18), // (28,18): error CS0523: Struct member 'S5<T>.x' of type 'S5<S5<T>.E>' causes a cycle in the struct layout // static S5<E> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S5<T>.x", "S5<S5<T>.E>").WithLocation(28, 18), // (32,20): error CS0523: Struct member 'S6<T>.x' of type 'S6<T[]>' causes a cycle in the struct layout // static S6<T[]> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S6<T>.x", "S6<T[]>").WithLocation(32, 20), // (8,18): warning CS0169: The field 'S1<T>.x' is never used // static S1<C> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(8, 18), // (23,18): warning CS0169: The field 'S4<T>.x' is never used // static S4<D> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S4<T>.x").WithLocation(23, 18), // (18,18): warning CS0169: The field 'S3<T>.x' is never used // static S3<I> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S3<T>.x").WithLocation(18, 18), // (3,18): warning CS0169: The field 'S0<T>.x' is never used // static S0<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S0<T>.x").WithLocation(3, 18), // (13,18): warning CS0169: The field 'S2<T>.x' is never used // static S2<S> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S2<T>.x").WithLocation(13, 18), // (28,18): warning CS0169: The field 'S5<T>.x' is never used // static S5<E> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S5<T>.x").WithLocation(28, 18), // (32,20): warning CS0169: The field 'S6<T>.x' is never used // static S6<T[]> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S6<T>.x").WithLocation(32, 20)); } [Fact] public void CS0524ERR_InterfacesCannotContainTypes01() { var text = @"namespace NS { public interface IGoo { interface IBar { } public class cly {} struct S { } private enum E { zero, one } // internal delegate void MyDel(object p); // delegates not in scope yet } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (5,19): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // interface IBar { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "IBar").WithArguments("default interface implementation", "8.0").WithLocation(5, 19), // (6,22): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // public class cly {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "cly").WithArguments("default interface implementation", "8.0").WithLocation(6, 22), // (7,16): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // struct S { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "S").WithArguments("default interface implementation", "8.0").WithLocation(7, 16), // (8,22): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // private enum E { zero, one } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "E").WithArguments("default interface implementation", "8.0").WithLocation(8, 22) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0525ERR_InterfacesCantContainFields01() { var text = @"namespace NS { public interface IGoo { string field1; const ulong field2 = 0; public IGoo field3; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,16): error CS0525: Interfaces cannot contain instance fields // string field1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "field1").WithLocation(5, 16), // (6,21): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // const ulong field2 = 0; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "field2").WithArguments("default interface implementation", "8.0").WithLocation(6, 21), // (7,21): error CS0525: Interfaces cannot contain instance fields // public IGoo field3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "field3").WithLocation(7, 21) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0526ERR_InterfacesCantContainConstructors01() { var text = @"namespace NS { public interface IGoo { public IGoo() {} internal IGoo(object p1, ref long p2) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 5, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 6, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0527ERR_NonInterfaceInInterfaceList01() { var text = @"namespace NS { class C { } public struct S : object, C { interface IGoo : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 7, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0528ERR_DuplicateInterfaceInBaseList01() { var text = @"namespace NS { public interface IGoo {} public interface IBar { } public class C : IGoo, IGoo { } struct S : IBar, IGoo, IBar { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 5, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 8, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Extra errors - expected /// </summary> [Fact] public void CS0529ERR_CycleInInterfaceInheritance01() { var text = @"namespace NS { class AA : BB { } class BB : CC { } class CC : I3 { } interface I1 : I2 { } interface I2 : I3 { } interface I3 : I1 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 7, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 8, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 9, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0531ERR_InterfaceMemberHasBody01() { var text = @"namespace NS { public interface IGoo { int M1() { return 0; } // CS0531 void M2<T>(T t) { } object P { get { return null; } } } interface IBar<T, V> { V M1(T t) { return default(V); } void M2(ref T t, out V v) { v = default(V); } T P { get { return default(T) } set { } } } } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (14,39): error CS1002: ; expected // T P { get { return default(T) } set { } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(14, 39) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void AbstractConstructor() { var text = @"namespace NS { public class C { abstract C(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 5, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void StaticFixed() { var text = @"unsafe struct S { public static fixed int x[10]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'static' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("static")); } [WorkItem(895401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895401")] [Fact] public void VolatileFixed() { var text = @"unsafe struct S { public volatile fixed int x[10]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'volatile' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile")); } [WorkItem(895401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895401")] [Fact] public void ReadonlyConst() { var text = @" class C { private readonly int F1 = 123; private const int F2 = 123; private readonly const int F3 = 123; }"; CreateCompilation(text).VerifyDiagnostics( // (6,32): error CS0106: The modifier 'readonly' is not valid for this item // private readonly const int F3 = 123; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F3").WithArguments("readonly"), // (4,26): warning CS0414: The field 'C.F1' is assigned but its value is never used // private readonly int F1 = 123; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F1").WithArguments("C.F1")); } [Fact] public void CS0533ERR_HidingAbstractMethod() { var text = @"namespace x { abstract public class a { abstract public void f(); abstract public void g(); } abstract public class b : a { new abstract public void f(); // CS0533 new abstract internal void g(); //fine since internal public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 34 }); } [WorkItem(539629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539629")] [Fact] public void CS0533ERR_HidingAbstractMethod02() { var text = @" abstract public class B1 { public abstract float goo { set; } } abstract class A1 : B1 { new protected enum goo { } // CS0533 abstract public class B2 { protected abstract void goo(); } abstract class A2 : B2 { new public delegate object goo(); // CS0533 } } namespace NS { abstract public class B3 { public abstract void goo(); } abstract class A3 : B3 { new protected double[] goo; // CS0533 } } "; CreateCompilation(text).VerifyDiagnostics( // (31,32): error CS0533: 'A3.goo' hides inherited abstract member 'B3.goo()' // new protected double[] goo; // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("NS.A3.goo", "NS.B3.goo()").WithLocation(31, 32), // (9,24): error CS0533: 'A1.goo' hides inherited abstract member 'B1.goo' // new protected enum goo { } // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("A1.goo", "B1.goo").WithLocation(9, 24), // (18,36): error CS0533: 'A1.A2.goo' hides inherited abstract member 'A1.B2.goo()' // new public delegate object goo(); // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("A1.A2.goo", "A1.B2.goo()").WithLocation(18, 36), // (31,32): warning CS0649: Field 'A3.goo' is never assigned to, and will always have its default value null // new protected double[] goo; // CS0533 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "goo").WithArguments("NS.A3.goo", "null").WithLocation(31, 32)); } [WorkItem(540464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540464")] [Fact] public void CS0533ERR_HidingAbstractMethod03() { var text = @" public abstract class A { public abstract void f(); public abstract void g(); public abstract void h(); } public abstract class B : A { public override void g() { } } public abstract class C : B { public void h(int a) { } } public abstract class D: C { public new int f; // expected CS0533: 'C.f' hides inherited abstract member 'A.f()' public new int g; // no error public new int h; // no CS0533 here in Dev10, but I'm not sure why not. (VB gives error for this case) } "; CreateCompilation(text).VerifyDiagnostics( // (18,16): error CS0533: 'D.f' hides inherited abstract member 'A.f()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "f").WithArguments("D.f", "A.f()")); } [WorkItem(539629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539629")] [Fact] public void CS0533ERR_HidingAbstractMethod_Combinations() { var text = @" abstract class Base { public abstract void M(); public abstract int P { get; set; } public abstract class C { } } abstract class Derived1 : Base { public new abstract void M(); public new abstract void P(); public new abstract void C(); } abstract class Derived2 : Base { public new abstract int M { get; set; } public new abstract int P { get; set; } public new abstract int C { get; set; } } abstract class Derived3 : Base { public new abstract class M { } public new abstract class P { } public new abstract class C { } } abstract class Derived4 : Base { public new void M() { } public new void P() { } public new void C() { } } abstract class Derived5 : Base { public new int M { get; set; } public new int P { get; set; } public new int C { get; set; } } abstract class Derived6 : Base { public new class M { } public new class P { } public new class C { } } abstract class Derived7 : Base { public new static void M() { } public new static int P { get; set; } public new static class C { } } abstract class Derived8 : Base { public new static int M = 1; public new static class P { }; public new const int C = 2; }"; // CONSIDER: dev10 reports each hidden accessor separately, but that seems silly CreateCompilation(text).VerifyDiagnostics( // (11,30): error CS0533: 'Derived1.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived1.M()", "Base.M()"), // (12,30): error CS0533: 'Derived1.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived1.P()", "Base.P"), // (18,29): error CS0533: 'Derived2.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived2.M", "Base.M()"), // (19,29): error CS0533: 'Derived2.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived2.P", "Base.P"), // (25,31): error CS0533: 'Derived3.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived3.M", "Base.M()"), // (26,31): error CS0533: 'Derived3.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived3.P", "Base.P"), // (32,21): error CS0533: 'Derived4.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived4.M()", "Base.M()"), // (33,21): error CS0533: 'Derived4.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived4.P()", "Base.P"), // (39,20): error CS0533: 'Derived5.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived5.M", "Base.M()"), // (40,20): error CS0533: 'Derived5.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived5.P", "Base.P"), // (46,22): error CS0533: 'Derived6.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived6.M", "Base.M()"), // (47,22): error CS0533: 'Derived6.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived6.P", "Base.P"), // (53,28): error CS0533: 'Derived7.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived7.M()", "Base.M()"), // (54,27): error CS0533: 'Derived7.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived7.P", "Base.P"), // (60,27): error CS0533: 'Derived8.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived8.M", "Base.M()"), // (61,20): error CS0533: 'Derived8.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived8.P", "Base.P")); } [WorkItem(539585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539585")] [Fact] public void CS0534ERR_UnimplementedAbstractMethod() { var text = @" abstract class A<T> { public abstract void M(T t); } abstract class B<T> : A<T> { public abstract void M(string s); } class C : B<string> // CS0534 { public override void M(string s) { } static void Main() { } } public abstract class Base<T> { public abstract void M(T t); public abstract void M(int i); } public class Derived : Base<int> // CS0534 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 13, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }); } [Fact] public void CS0535ERR_UnimplementedInterfaceMember() { var text = @"public interface A { void F(); } public class B : A { } // CS0535 A::F is not implemented "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 18 }); } [Fact] public void CS0537ERR_ObjectCantHaveBases() { var text = @"namespace System { public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateEmptyCompilation(text).VerifyDiagnostics( // (3,20): error CS0246: The type or namespace name 'ICloneable' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ICloneable").WithArguments("ICloneable"), // (3,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } //this should be the same as CS0537ERR_ObjectCantHaveBases, except without the second //error (about ICloneable not being defined) [Fact] public void CS0537ERR_ObjectCantHaveBases_OtherType() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateEmptyCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact] public void CS0537ERR_ObjectCantHaveBases_WithMsCorlib() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; // When System.Object is defined in both source and metadata, dev10 favors // the source version and reports ERR_ObjectCantHaveBases. CreateEmptyCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [Fact] public void CS0538ERR_ExplicitInterfaceImplementationNotInterface() { var text = @"interface MyIFace { } public class MyClass { } class C : MyIFace { void MyClass.G() // CS0538, MyClass not an interface { } int MyClass.P { get { return 1; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 11, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 14, Column = 9 }); } [Fact] public void CS0539ERR_InterfaceMemberNotFound() { var text = @"namespace x { interface I { void m(); } public class clx : I { void I.x() // CS0539 { } void I.m() { } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberNotFound, Line = 10, Column = 14 }); } [Fact] public void CS0540ERR_ClassDoesntImplementInterface() { var text = @"interface I { void m(); } public class Clx { void I.m() { } // CS0540 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ClassDoesntImplementInterface, Line = 8, Column = 10 }); } [Fact] public void CS0541ERR_ExplicitInterfaceImplementationInNonClassOrStruct() { var text = @"namespace x { interface IFace { void F(); int P { set; } } interface IFace2 : IFace { void IFace.F(); // CS0541 int IFace.P { set; } //CS0541 } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (11,20): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // void IFace.F(); // CS0541 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "F").WithArguments("default interface implementation", "8.0").WithLocation(11, 20), // (12,23): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // int IFace.P { set; } //CS0541 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 23), // (12,23): error CS0501: 'IFace2.IFace.P.set' must declare a body because it is not marked abstract, extern, or partial // int IFace.P { set; } //CS0541 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("x.IFace2.x.IFace.P.set").WithLocation(12, 23), // (11,20): error CS0501: 'IFace2.IFace.F()' must declare a body because it is not marked abstract, extern, or partial // void IFace.F(); // CS0541 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "F").WithArguments("x.IFace2.x.IFace.F()").WithLocation(11, 20) ); } [Fact] public void CS0542ERR_MemberNameSameAsType01() { var comp = CreateCompilation( @"namespace NS { class NS { } // no error interface IM { void IM(); } // no error interface IP { object IP { get; } } // no error enum A { A } // no error class B { enum B { } } class C { static void C() { } } class D { object D { get; set; } } class E { int D, E, F; } class F { class F { } } class G { struct G { } } class H { delegate void H(); } class L { class L<T> { } } class K<T> { class K { } } class M<T> { interface M<U> { } } class N { struct N<T, U> { } } struct O { enum O { } } struct P { void P() { } } struct Q { static object Q { get; set; } } struct R { object Q, R; } struct S { class S { } } struct T { interface T { } } struct U { struct U { } } struct V { delegate void V(); } struct W { class W<T> { } } struct X<T> { class X { } } struct Y<T> { interface Y<U> { } } struct Z { struct Z<T, U> { } } } "); comp.VerifyDiagnostics( // (7,20): error CS0542: 'B': member names cannot be the same as their enclosing type // class B { enum B { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "B").WithArguments("B"), // (8,27): error CS0542: 'C': member names cannot be the same as their enclosing type // class C { static void C() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C"), // (9,22): error CS0542: 'D': member names cannot be the same as their enclosing type // class D { object D { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "D").WithArguments("D"), // (10,22): error CS0542: 'E': member names cannot be the same as their enclosing type // class E { int D, E, F; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("E"), // (11,21): error CS0542: 'F': member names cannot be the same as their enclosing type // class F { class F { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "F").WithArguments("F"), // (12,22): error CS0542: 'G': member names cannot be the same as their enclosing type // class G { struct G { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "G").WithArguments("G"), // (13,29): error CS0542: 'H': member names cannot be the same as their enclosing type // class H { delegate void H(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "H").WithArguments("H"), // (14,21): error CS0542: 'L': member names cannot be the same as their enclosing type // class L { class L<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "L").WithArguments("L"), // (15,24): error CS0542: 'K': member names cannot be the same as their enclosing type // class K<T> { class K { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "K").WithArguments("K"), // (16,28): error CS0542: 'M': member names cannot be the same as their enclosing type // class M<T> { interface M<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "M").WithArguments("M"), // (17,22): error CS0542: 'N': member names cannot be the same as their enclosing type // class N { struct N<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "N").WithArguments("N"), // (18,21): error CS0542: 'O': member names cannot be the same as their enclosing type // struct O { enum O { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "O").WithArguments("O"), // (19,21): error CS0542: 'P': member names cannot be the same as their enclosing type // struct P { void P() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "P").WithArguments("P"), // (20,30): error CS0542: 'Q': member names cannot be the same as their enclosing type // struct Q { static object Q { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Q").WithArguments("Q"), // (21,26): error CS0542: 'R': member names cannot be the same as their enclosing type // struct R { object Q, R; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "R").WithArguments("R"), // (22,22): error CS0542: 'S': member names cannot be the same as their enclosing type // struct S { class S { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "S").WithArguments("S"), // (23,26): error CS0542: 'T': member names cannot be the same as their enclosing type // struct T { interface T { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "T").WithArguments("T"), // (24,23): error CS0542: 'U': member names cannot be the same as their enclosing type // struct U { struct U { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "U").WithArguments("U"), // (25,30): error CS0542: 'V': member names cannot be the same as their enclosing type // struct V { delegate void V(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "V").WithArguments("V"), // (26,22): error CS0542: 'W': member names cannot be the same as their enclosing type // struct W { class W<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "W").WithArguments("W"), // (27,25): error CS0542: 'X': member names cannot be the same as their enclosing type // struct X<T> { class X { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "X").WithArguments("X"), // (28,29): error CS0542: 'Y': member names cannot be the same as their enclosing type // struct Y<T> { interface Y<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Y").WithArguments("Y"), // (29,23): error CS0542: 'Z': member names cannot be the same as their enclosing type // struct Z { struct Z<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Z").WithArguments("Z"), // (10,19): warning CS0169: The field 'NS.E.D' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "D").WithArguments("NS.E.D"), // (10,22): warning CS0169: The field 'NS.E.E' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "E").WithArguments("NS.E.E"), // (10,25): warning CS0169: The field 'NS.E.F' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("NS.E.F"), // (21,23): warning CS0169: The field 'NS.R.Q' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("NS.R.Q"), // (21,26): warning CS0169: The field 'NS.R.R' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "R").WithArguments("NS.R.R")); } [Fact] public void CS0542ERR_MemberNameSameAsType02() { // No errors for names from explicit implementations. var source = @"interface IM { void C(); } interface IP { object C { get; } } class C : IM, IP { void IM.C() { } object IP.C { get { return null; } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact(), WorkItem(529156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529156")] public void CS0542ERR_MemberNameSameAsType03() { CreateCompilation( @"class Item { public int this[int i] // CS0542 { get { return 0; } } } ").VerifyDiagnostics(); } [WorkItem(538633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538633")] [Fact] public void CS0542ERR_MemberNameSameAsType04() { var source = @"class get_P { object P { get; set; } // CS0542 } class set_P { object P { set { } } // CS0542 } interface get_Q { object Q { get; } } class C : get_Q { public object Q { get; set; } } interface IR { object R { get; set; } } class get_R : IR { public object R { get; set; } // CS0542 } class set_R : IR { object IR.R { get; set; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,16): error CS0542: 'get_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_P").WithLocation(3, 16), // (7,16): error CS0542: 'set_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_P").WithLocation(7, 16), // (23,23): error CS0542: 'get_R': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_R").WithLocation(23, 23)); } [Fact] public void CS0542ERR_MemberNameSameAsType05() { var source = @"namespace N1 { class get_Item { object this[object o] { get { return null; } set { } } // CS0542 } class set_Item { object this[object o] { get { return null; } set { } } // CS0542 } } namespace N2 { interface I { object this[object o] { get; set; } } class get_Item : I { public object this[object o] { get { return null; } set { } } // CS0542 } class set_Item : I { object I.this[object o] { get { return null; } set { } } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,33): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(5, 33), // (9,54): error CS0542: 'set_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_Item").WithLocation(9, 54), // (20,40): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(20, 40)); } /// <summary> /// Derived class with same name as base class /// property accessor metadata name. /// </summary> [Fact] public void CS0542ERR_MemberNameSameAsType06() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object B1() { } .method public abstract virtual instance void B2(object v) { } .property instance object P() { .get instance object A::B1() .set instance void A::B2(object v) } }"; var reference1 = CompileIL(source1); var source2 = @"class B0 : A { public override object P { get { return null; } set { } } } class B1 : A { public override object P { get { return null; } set { } } } class B2 : A { public override object P { get { return null; } set { } } } class get_P : A { public override object P { get { return null; } set { } } } class set_P : A { public override object P { get { return null; } set { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (72): error CS0542: 'B1': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("B1").WithLocation(7, 32), // (11,53): error CS0542: 'B2': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("B2").WithLocation(11, 53)); } /// <summary> /// Derived class with same name as base class /// event accessor metadata name. /// </summary> [WorkItem(530385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530385")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CS0542ERR_MemberNameSameAsType07() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance void B1(class [mscorlib]System.Action v) { } .method public abstract virtual instance void B2(class [mscorlib]System.Action v) { } .event [mscorlib]System.Action E { .addon instance void A::B1(class [mscorlib]System.Action); .removeon instance void A::B2(class [mscorlib]System.Action); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class B0 : A { public override event Action E; } class B1 : A { public override event Action E; } class B2 : A { public override event Action E; } class add_E : A { public override event Action E; } class remove_E : A { public override event Action E; }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,34): error CS0542: 'B1': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B1").WithLocation(8, 34), // (12,34): error CS0542: 'B2': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B2").WithLocation(12, 34), // (16,34): warning CS0067: The event 'add_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("add_E.E").WithLocation(16, 34), // (12,34): warning CS0067: The event 'B2.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B2.E").WithLocation(12, 34), // (8,34): warning CS0067: The event 'B1.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B1.E").WithLocation(8, 34), // (20,34): warning CS0067: The event 'remove_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("remove_E.E").WithLocation(20, 34), // (4,34): warning CS0067: The event 'B0.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B0.E").WithLocation(4, 34)); } [Fact] public void CS0544ERR_CantOverrideNonProperty() { var text = @"public class a { public int i; } public class b : a { public override int i// CS0544 { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonProperty, Line = 8, Column = 25 }); } [Fact] public void CS0545ERR_NoGetToOverride() { var text = @"public class a { public virtual int i { set { } } } public class b : a { public override int i { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 13, Column = 9 }); } [WorkItem(539321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539321")] [Fact] public void CS0545ERR_NoGetToOverride_Regress() { var text = @"public class A { public virtual int P1 { private get; set; } public virtual int P2 { private get; set; } } public class C : A { public override int P1 { set { } } //fine public sealed override int P2 { set { } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,32): error CS0545: 'C.P2': cannot override because 'A.P2' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.SetMethod.IsVirtual); Assert.False(classAProp1.GetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0546ERR_NoSetToOverride() { var text = @"public class a { public virtual int i { get { return 0; } } } public class b : a { public override int i { set { } // CS0546 error no set } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 15, Column = 9 }); } [WorkItem(539321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539321")] [Fact] public void CS0546ERR_NoSetToOverride_Regress() { var text = @"public class A { public virtual int P1 { get; private set; } public virtual int P2 { get; private set; } } public class C : A { public override int P1 { get { return 0; } } //fine public sealed override int P2 { get { return 0; } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,32): error CS0546: 'C.P2': cannot override because 'A.P2' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.GetMethod.IsVirtual); Assert.False(classAProp1.SetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0547ERR_PropertyCantHaveVoidType() { var text = @"interface I { void P { get; set; } } class C { internal void P { set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 3, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 7, Column = 19 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors() { var text = @"interface I { object P { } } abstract class A { public abstract object P { } } class B { internal object P { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors_Indexer() { var text = @"interface I { object this[int x] { } } abstract class A { public abstract object this[int x] { } } class B { internal object this[int x] { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0549ERR_NewVirtualInSealed01() { var text = @"namespace NS { public sealed class Goo { public virtual void M1() { } internal virtual void M2<X>(X x) { } internal virtual int P1 { get; set; } } sealed class Bar<T> { internal virtual T M1(T t) { return t; } public virtual object P1 { get { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 12, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 13, Column = 36 }); } [Fact] public void CS0549ERR_NewVirtualInSealed02() { var text = @" public sealed class C { public virtual event System.Action E; public virtual event System.Action F { add { } remove { } } public virtual int this[int x] { get { return 0; } set { } } } "; // CONSIDER: it seems a little strange to report it on property accessors but on // events themselves. On the other hand, property accessors can have modifiers, // whereas event accessors cannot. CreateCompilation(text).VerifyDiagnostics( // (4,40): error CS0549: 'C.E' is a new virtual member in sealed type 'C' // public virtual event System.Action E; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "E").WithArguments("C.E", "C"), // (5,40): error CS0549: 'C.F' is a new virtual member in sealed type 'C' // public virtual event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "F").WithArguments("C.F", "C"), // (6,38): error CS0549: 'C.this[int].get' is a new virtual member in sealed type 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "get").WithArguments("C.this[int].get", "C"), // (6,56): error CS0549: 'C.this[int].set' is a new virtual member in sealed type 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "set").WithArguments("C.this[int].set", "C"), // (4,40): warning CS0067: The event 'C.E' is never used // public virtual event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0550ERR_ExplicitPropertyAddingAccessor() { var text = @"namespace x { interface ii { int i { get; } } public class a : ii { int ii.i { get { return 0; } set { } // CS0550 no set in interface } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 19, Column = 13 }); } [Fact] public void CS0551ERR_ExplicitPropertyMissingAccessor() { var text = @"interface ii { int i { get; set; } } public class a : ii { int ii.i { set { } } // CS0551 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 10, Column = 18 }, //CONSIDER: dev10 suppresses this new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 12, Column = 12 }); } [Fact] public void CS0552ERR_ConversionWithInterface() { var text = @" public interface I { } public class C { public static implicit operator I(C c) // CS0552 { return null; } public static implicit operator C(I i) // CS0552 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (77): error CS0552: 'C.implicit operator I(C)': user-defined conversions to or from an interface are not allowed // public static implicit operator I(C c) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I").WithArguments("C.implicit operator I(C)"), // (11,37): error CS0552: 'C.implicit operator C(I)': user-defined conversions to or from an interface are not allowed // public static implicit operator C(I i) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "C").WithArguments("C.implicit operator C(I)")); } [Fact] public void CS0553ERR_ConversionWithBase() { var text = @" public class B { } public class D : B { public static implicit operator B(D d) // CS0553 { return null; } } public struct C { public static implicit operator C?(object c) // CS0553 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,37): error CS0553: 'D.implicit operator B(D)': user-defined conversions to or from a base type are not allowed // public static implicit operator B(D d) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "B").WithArguments("D.implicit operator B(D)"), // (12,37): error CS0553: 'C.implicit operator C?(object)': user-defined conversions to or from a base type are not allowed // public static implicit operator C?(object c) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "C?").WithArguments("C.implicit operator C?(object)")); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public class B { public static implicit operator B(D d) // CS0554 { return null; } } public class D : B {} "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0555ERR_IdentityConversion() { var text = @" public class MyClass { public static implicit operator MyClass(MyClass aa) // CS0555 { return new MyClass(); } } public struct S { public static implicit operator S?(S s) { return s; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0555: User-defined operator cannot convert a type to itself // public static implicit operator MyClass(MyClass aa) // CS0555 Diagnostic(ErrorCode.ERR_IdentityConversion, "MyClass"), // (11,37): error CS0555: User-defined operator cannot convert a type to itself // public static implicit operator S?(S s) { return s; } Diagnostic(ErrorCode.ERR_IdentityConversion, "S?") ); } [Fact] public void CS0556ERR_ConversionNotInvolvingContainedType() { var text = @" public class C { public static implicit operator int(string aa) // CS0556 { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator int(string aa) // CS0556 Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int") ); } [Fact] public void CS0557ERR_DuplicateConversionInClass() { var text = @"namespace x { public class ii { public class iii { public static implicit operator int(iii aa) { return 0; } public static explicit operator int(iii aa) { return 0; } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,45): error CS0557: Duplicate user-defined conversion in type 'x.ii.iii' // public static explicit operator int(iii aa) Diagnostic(ErrorCode.ERR_DuplicateConversionInClass, "int").WithArguments("x.ii.iii") ); } [Fact] public void CS0558ERR_OperatorsMustBeStatic() { var text = @"namespace x { public class ii { public class iii { static implicit operator int(iii aa) // CS0558, add public { return 0; } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (75): error CS0558: User-defined operator 'x.ii.iii.implicit operator int(x.ii.iii)' must be declared static and public // static implicit operator int(iii aa) // CS0558, add public Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("x.ii.iii.implicit operator int(x.ii.iii)") ); } [Fact] public void CS0559ERR_BadIncDecSignature() { var text = @"public class iii { public static iii operator ++(int aa) // CS0559 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static iii operator ++(int aa) // CS0559 Diagnostic(ErrorCode.ERR_BadIncDecSignature, "++")); } [Fact] public void CS0562ERR_BadUnaryOperatorSignature() { var text = @"public class iii { public static iii operator +(int aa) // CS0562 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0562: The parameter of a unary operator must be the containing type // public static iii operator +(int aa) // CS0562 Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "+") ); } [Fact] public void CS0563ERR_BadBinaryOperatorSignature() { var text = @"public class iii { public static int operator +(int aa, int bb) // CS0563 { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0563: One of the parameters of a binary operator must be the containing type // public static int operator +(int aa, int bb) // CS0563 Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+") ); } [Fact] public void CS0564ERR_BadShiftOperatorSignature() { var text = @" class C { public static int operator <<(C c1, C c2) // CS0564 { return 0; } public static int operator >>(int c1, int c2) // CS0564 { return 0; } static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator <<(C c1, C c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<"), // (8,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator >>(int c1, int c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>") ); } [Fact] public void CS0567ERR_InterfacesCantContainOperators() { var text = @" interface IA { int operator +(int aa, int bb); // CS0567 } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (4,17): error CS0558: User-defined operator 'IA.operator +(int, int)' must be declared static and public // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("IA.operator +(int, int)").WithLocation(4, 17), // (4,17): error CS0501: 'IA.operator +(int, int)' must declare a body because it is not marked abstract, extern, or partial // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("IA.operator +(int, int)").WithLocation(4, 17), // (4,17): error CS0563: One of the parameters of a binary operator must be the containing type // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+").WithLocation(4, 17) ); } [Fact] public void CS0569ERR_CantOverrideBogusMethod() { var source1 = @".class abstract public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_sealed() { } .method public abstract virtual instance void set_sealed(object o) { } } .class abstract public B extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_abstract() { } .method public abstract virtual instance void set_abstract(object o) { } .method public virtual final instance void set_sealed(object o) { ret } .method public virtual final instance object get_sealed() { ldnull ret } // abstract get, sealed set .property instance object P() { .get instance object B::get_abstract() .set instance void B::set_sealed(object) } // sealed get, abstract set .property instance object Q() { .get instance object B::get_sealed() .set instance void B::set_abstract(object) } }"; var reference1 = CompileIL(source1); var source2 = @"class C : B { public override object P { get { return 0; } } public override object Q { set { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (3,28): error CS0569: 'C.P': cannot override 'B.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "P").WithArguments("C.P", "B.P").WithLocation(3, 28), // (4,28): error CS0569: 'C.Q': cannot override 'B.Q' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Q").WithArguments("C.Q", "B.Q").WithLocation(4, 28)); } [Fact] public void CS8036ERR_FieldInitializerInStruct() { var text = @"namespace x { public class clx { public static void Main() { } } public struct cly { clx a = new clx(); // CS8036 int i = 7; // CS8036 const int c = 1; // no error static int s = 2; // no error } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,13): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // clx a = new clx(); // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(12, 13), // (13,13): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // int i = 7; // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "i").WithArguments("struct field initializers", "10.0").WithLocation(13, 13), // (13,13): warning CS0414: The field 'cly.i' is assigned but its value is never used // int i = 7; // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("x.cly.i").WithLocation(13, 13), // (15,20): warning CS0414: The field 'cly.s' is assigned but its value is never used // static int s = 2; // no error Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("x.cly.s").WithLocation(15, 20)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,13): warning CS0414: The field 'cly.i' is assigned but its value is never used // int i = 7; // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("x.cly.i").WithLocation(13, 13), // (15,20): warning CS0414: The field 'cly.s' is assigned but its value is never used // static int s = 2; // no error Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("x.cly.s").WithLocation(15, 20)); } [Fact] public void CS0568ERR_StructsCantContainDefaultConstructor01() { var text = @"namespace x { public struct S1 { public S1() {} struct S2<T> { S2() { } } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)); comp.VerifyDiagnostics( // (5,16): error CS8026: Feature 'parameterless struct constructors' is not available in C# 5. Please use language version 10.0 or greater. // public S1() {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 16), // (9,13): error CS8026: Feature 'parameterless struct constructors' is not available in C# 5. Please use language version 10.0 or greater. // S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(9, 13), // (9,13): error CS8938: The parameterless struct constructor must be 'public'. // S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(9, 13)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,13): error CS8918: The parameterless struct constructor must be 'public'. // S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(9, 13)); } [Fact] public void CS0575ERR_OnlyClassesCanContainDestructors() { var text = @"namespace x { public struct iii { ~iii() // CS0575 { } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OnlyClassesCanContainDestructors, Line = 5, Column = 10 }); } [Fact] public void CS0576ERR_ConflictAliasAndMember01() { var text = @"namespace NS { class B { } } namespace NS { using System; using B = NS.B; class A { public static void Main(String[] args) { B b = null; if (b == b) {} } } struct S { B field; public void M(ref B p) { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,27): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // public void M(ref B p) { } Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,9): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B field; Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (15,13): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B b = null; if (b == b) {} Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,11): warning CS0169: The field 'NS.S.field' is never used // B field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(545463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545463")] [Fact] public void CS0576ERR_ConflictAliasAndMember02() { var source = @" namespace Globals.Errors.ResolveInheritance { using ConflictingAlias = BadUsingNamespace; public class ConflictingAlias { public class Nested { } } namespace BadUsingNamespace { public class UsingNotANamespace { } } class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error class Cls2 : ConflictingAlias::UsingNotANamespace { } // OK class Cls3 : global::Globals.Errors.ResolveInheritance.ConflictingAlias.Nested { } // OK } "; CreateCompilation(source).VerifyDiagnostics( // (12,18): error CS0576: Namespace 'Globals.Errors.ResolveInheritance' contains a definition conflicting with alias 'ConflictingAlias' // class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "ConflictingAlias").WithArguments("ConflictingAlias", "Globals.Errors.ResolveInheritance")); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_01() { var sourceA = @"#pragma warning disable 436 using System.Diagnostics; class Program { [Conditional("""")] Program() { } }"; var sourceB = @"namespace System.Diagnostics { public class ConditionalAttribute : Attribute { public ConditionalAttribute(string s) { } } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,6): error CS0577: The Conditional attribute is not valid on 'Program.Program()' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [Conditional("")] Program() { } Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional("""")").WithArguments("Program.Program()").WithLocation(5, 6)); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_02() { var source = @"using System.Diagnostics; class Program { [Conditional("""")] ~Program() { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,6): error CS0577: The Conditional attribute is not valid on 'Program.~Program()' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [Conditional("")] ~Program() { } Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional("""")").WithArguments("Program.~Program()").WithLocation(4, 6)); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_03() { var source = @"using System.Diagnostics; class C { [Conditional("""")] public static C operator !(C c) => c; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,6): error CS0577: The Conditional attribute is not valid on 'C.operator !(C)' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [Conditional("")] public static C operator !(C c) => c; Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional("""")").WithArguments("C.operator !(C)").WithLocation(4, 6)); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_04() { var text = @"interface I { void m(); } public class MyClass : I { [System.Diagnostics.Conditional(""a"")] // CS0577 void I.m() { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,6): error CS0577: The Conditional attribute is not valid on 'MyClass.I.m()' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [System.Diagnostics.Conditional("a")] // CS0577 Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"System.Diagnostics.Conditional(""a"")").WithArguments("MyClass.I.m()").WithLocation(8, 6)); } [Fact] public void CS0578ERR_ConditionalMustReturnVoid() { var text = @"public class MyClass { [System.Diagnostics.ConditionalAttribute(""a"")] // CS0578 public int TestMethod() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,5): error CS0578: The Conditional attribute is not valid on 'MyClass.TestMethod()' because its return type is not void // [System.Diagnostics.ConditionalAttribute("a")] // CS0578 Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"System.Diagnostics.ConditionalAttribute(""a"")").WithArguments("MyClass.TestMethod()").WithLocation(3, 5)); } [Fact] public void CS0579ERR_DuplicateAttribute() { var text = @"class A : System.Attribute { } class B : System.Attribute { } [A, A] class C { } [B][A][B] class D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 3, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 4, Column = 8 }); } [Fact, WorkItem(528872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528872")] public void CS0582ERR_ConditionalOnInterfaceMethod() { var text = @"using System.Diagnostics; interface MyIFace { [ConditionalAttribute(""DEBUG"")] // CS0582 void zz(); } "; CreateCompilation(text).VerifyDiagnostics( // (4,5): error CS0582: The Conditional attribute is not valid on interface members // [ConditionalAttribute("DEBUG")] // CS0582 Diagnostic(ErrorCode.ERR_ConditionalOnInterfaceMethod, @"ConditionalAttribute(""DEBUG"")").WithLocation(4, 5)); } [Fact] public void CS0590ERR_OperatorCantReturnVoid() { var text = @" public class C { public static void operator +(C c1, C c2) { } public static implicit operator void(C c1) { } public static void operator +(C c) { } public static void operator >>(C c, int x) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c1, C c2) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (5,33): error CS0590: User-defined operators cannot return void // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "void"), // (5,46): error CS1547: Keyword 'void' cannot be used in this context // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (6,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (73): error CS0590: User-defined operators cannot return void // public static void operator >>(C c, int x) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>") ); } [Fact] public void CS0591ERR_InvalidAttributeArgument() { var text = @"using System; [AttributeUsage(0)] // CS0591 class A : Attribute { } [AttributeUsageAttribute(0)] // CS0591 class B : Attribute { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (2,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsage").WithLocation(2, 17), // (4,26): error CS0591: Invalid value for argument to 'AttributeUsageAttribute' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsageAttribute").WithLocation(4, 26)); } [Fact] public void CS0592ERR_AttributeOnBadSymbolType() { var text = @"using System; [AttributeUsage(AttributeTargets.Interface)] public class MyAttribute : Attribute { } [MyAttribute] // Generates CS0592 because MyAttribute is not valid for a class. public class A { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttributeOnBadSymbolType, Line = 8, Column = 2 }); } [Fact()] public void CS0596ERR_ComImportWithoutUuidAttribute() { var text = @"using System.Runtime.InteropServices; namespace x { [ComImport] // CS0596 public class a { } public class b { public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ComImportWithoutUuidAttribute, Line = 5, Column = 6 }); } // CS0599: not used [Fact] public void CS0601ERR_DllImportOnInvalidMethod() { var text = @" using System.Runtime.InteropServices; public class C { [DllImport(""KERNEL32.DLL"")] extern int Goo(); // CS0601 [DllImport(""KERNEL32.DLL"")] static void Bar() { } // CS0601 } "; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), // (9,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport")); } /// <summary> /// Dev10 doesn't report this error, but emits invalid metadata. /// When the containing type is being loaded TypeLoadException is thrown by the CLR. /// </summary> [Fact] public void CS7042ERR_DllImportOnGenericMethod() { var text = @" using System.Runtime.InteropServices; public class C<T> { class X { [DllImport(""KERNEL32.DLL"")] static extern void Bar(); } } public class C { [DllImport(""KERNEL32.DLL"")] static extern void Bar<T>(); } "; CreateCompilation(text).VerifyDiagnostics( // (8,10): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport"), // (15,6): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport")); } // CS0609ERR_NameAttributeOnOverride -> BreakChange [Fact] public void CS0610ERR_FieldCantBeRefAny() { var text = @"public class MainClass { System.TypedReference i; // CS0610 public static void Main() { } System.TypedReference Prop { get; set; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference Prop { get; set; } Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,27): warning CS0169: The field 'MainClass.i' is never used // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("MainClass.i") ); } [Fact] public void CS0616ERR_NotAnAttributeClass() { var text = @"[CMyClass] // CS0616 public class CMyClass {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0616ERR_NotAnAttributeClass2() { var text = @"[CMyClass] // CS0616 public class CMyClassAttribute {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0617ERR_BadNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyClass : Attribute { public MyClass(int sName) { Bad = sName; Bad2 = -1; } public readonly int Bad; public int Bad2; } [MyClass(5, Bad = 0)] class Class1 { } // CS0617 [MyClass(5, Bad2 = 0)] class Class2 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgument, Line = 16, Column = 13 }); } [Fact] public void CS0620ERR_IndexerCantHaveVoidType() { var text = @"class MyClass { public static void Main() { MyClass test = new MyClass(); } void this[int intI] // CS0620, return type cannot be void { get { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerCantHaveVoidType, Line = 8, Column = 10 }); } [Fact] public void CS0621ERR_VirtualPrivate01() { var text = @"namespace x { class Goo { private virtual void vf() { } } public class Bar<T> { private virtual void M1(T t) { } virtual V M2<V>(T t); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 9, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("x").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0621ERR_VirtualPrivate02() { var source = @"abstract class A { abstract object P { get; } } class B { private virtual object Q { get; set; } } "; CreateCompilation(source).VerifyDiagnostics( // (3,21): error CS0621: 'A.P': virtual or abstract members cannot be private // abstract object P { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("A.P").WithLocation(3, 21), // (7,28): error CS0621: 'B.Q': virtual or abstract members cannot be private // private virtual object Q { get; set; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "Q").WithArguments("B.Q").WithLocation(7, 28)); } [Fact] public void CS0621ERR_VirtualPrivate03() { var text = @"namespace x { abstract class Goo { private virtual void M1<T>(T x) { } private abstract int P { get; set; } } class Bar { private override void M1<T>(T a) { } private override int P { set { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 6, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 11, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 11, Column = 30 }); } [Fact] public void CS0621ERR_VirtualPrivate04() { var text = @" class C { virtual private event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0621: 'C.E': virtual or abstract members cannot be private // virtual private event System.Action E; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E").WithArguments("C.E"), // (4,41): warning CS0067: The event 'C.E' is never used // virtual private event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } // CS0625: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0629ERR_InterfaceImplementedByConditional01() { var text = @"interface MyInterface { void MyMethod(); } public class MyClass : MyInterface { [System.Diagnostics.Conditional(""debug"")] public void MyMethod() // CS0629, remove the Conditional attribute { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceImplementedByConditional, Line = 9, Column = 17 }); } [Fact] public void CS0629ERR_InterfaceImplementedByConditional02() { var source = @" using System.Diagnostics; interface I<T> { void M(T x); } class Base { [Conditional(""debug"")] public void M(int x) {} } class Derived : Base, I<int> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,23): error CS0629: Conditional member 'Base.M(int)' cannot implement interface member 'I<int>.M(int)' in type 'Derived' // class Derived : Base, I<int> Diagnostic(ErrorCode.ERR_InterfaceImplementedByConditional, "I<int>").WithArguments("Base.M(int)", "I<int>.M(int)", "Derived").WithLocation(13, 23)); } [Fact] public void CS0633ERR_BadArgumentToAttribute() { var text = @"#define DEBUG using System.Diagnostics; public class Test { [Conditional(""DEB+UG"")] // CS0633 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'Conditional' attribute must be a valid identifier // [Conditional("DEB+UG")] // CS0633 Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""DEB+UG""").WithArguments("Conditional").WithLocation(5, 18)); } [Fact] public void CS0633ERR_BadArgumentToAttribute_IndexerNameAttribute() { var text = @" using System.Runtime.CompilerServices; class A { [IndexerName(null)] int this[int x] { get { return 0; } set { } } } class B { [IndexerName("""")] int this[int x] { get { return 0; } set { } } } class C { [IndexerName("" "")] int this[int x] { get { return 0; } set { } } } class D { [IndexerName(""1"")] int this[int x] { get { return 0; } set { } } } class E { [IndexerName(""!"")] int this[int x] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, "null").WithArguments("IndexerName"), // (10,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""""").WithArguments("IndexerName"), // (15,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @""" """).WithArguments("IndexerName"), // (20,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""1""").WithArguments("IndexerName"), // (25,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""!""").WithArguments("IndexerName")); } // CS0636: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors // CS0637: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0641ERR_AttributeUsageOnNonAttributeClass() { var text = @"using System; [AttributeUsage(AttributeTargets.Method)] class A { } [System.AttributeUsageAttribute(AttributeTargets.Class)] class B { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (2,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(2, 2), // (4,2): error CS0641: Attribute 'System.AttributeUsageAttribute' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "System.AttributeUsageAttribute").WithArguments("System.AttributeUsageAttribute").WithLocation(4, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyAttribute : Attribute { public MyAttribute() { } public int x; } [MyAttribute(x = 5, x = 6)] // CS0643, error setting x twice class MyClass { } public class MainClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNamedAttributeArgument, Line = 13, Column = 21 }); } [WorkItem(540923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540923")] [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { var text = @"using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (2,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(2, 39), // (2,2): error CS76: There is no argument given that corresponds to the required formal parameter 'validOn' of 'AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(2, 2) ); } [Fact] public void CS0644ERR_DeriveFromEnumOrValueType() { var source = @"using System; namespace N { class C : Enum { } class D : ValueType { } class E : Delegate { } static class F : MulticastDelegate { } static class G : Array { } } "; CreateCompilation(source).VerifyDiagnostics( // (5,15): error CS0644: 'D' cannot derive from special class 'ValueType' // class D : ValueType { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "ValueType").WithArguments("N.D", "System.ValueType").WithLocation(5, 15), // (6,15): error CS0644: 'E' cannot derive from special class 'Delegate' // class E : Delegate { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Delegate").WithArguments("N.E", "System.Delegate").WithLocation(6, 15), // (4,15): error CS0644: 'C' cannot derive from special class 'Enum' // class C : Enum { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Enum").WithArguments("N.C", "System.Enum").WithLocation(4, 15), // (8,22): error CS0644: 'G' cannot derive from special class 'Array' // static class G : Array { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Array").WithArguments("N.G", "System.Array").WithLocation(8, 22), // (7,22): error CS0644: 'F' cannot derive from special class 'MulticastDelegate' // static class F : MulticastDelegate { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "MulticastDelegate").WithArguments("N.F", "System.MulticastDelegate").WithLocation(7, 22)); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType() { var text = @"[System.Reflection.DefaultMemberAttribute(""x"")] // CS0646 class MyClass { public int this[int index] // an indexer { get { return 0; } } public int x = 0; } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultMemberOnIndexedType, Line = 1, Column = 2 }); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType02() { var text = @" using System.Reflection; interface I { int this[int x] { set; } } [DefaultMember(""X"")] class Program : I { int I.this[int x] { set { } } //doesn't count as an indexer for CS0646 }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType03() { var text = @" using System.Reflection; [DefaultMember(""This is definitely not a valid member name *#&#*"")] class Program { }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0653ERR_AbstractAttributeClass() { var text = @"using System; public abstract class MyAttribute : Attribute { } [My] // CS0653 class MyClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAttributeClass, Line = 7, Column = 2 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType() { var text = @"using System; class MyAttribute : Attribute { public decimal d = 0; public int e = 0; } [My(d = 0)] // CS0655 class C { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgumentType, Line = 9, Column = 5 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1(P = null)] // Dev11 error public class A1 : Attribute { public A1() { } public dynamic P { get; set; } } [A2(P = null)] // Dev11 ok (bug) public class A2 : Attribute { public A2() { } public dynamic[] P { get; set; } } [A3(P = 0)] // Dev11 error (bug) public class A3 : Attribute { public A3() { } public C<dynamic>.D P { get; set; } } [A4(P = null)] // Dev11 ok public class A4 : Attribute { public A4() { } public C<dynamic>.D[] P { get; set; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A1(P = null)] // Dev11 error Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P"), // (13,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A2(P = null)] // Dev11 ok (bug) Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P")); } [Fact] public void CS0656ERR_MissingPredefinedMember() { var text = @"namespace System { public class Object { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } public class Test { public unsafe static int Main() { string str = ""This is my test string""; fixed (char* ptr = str) { if (*(ptr + str.Length) != '\0') return 1; } return 0; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyEmitDiagnostics( // (70,32): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData' // fixed (char* ptr = str) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "str").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData")); } // CS0662: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0663ERR_OverloadRefOut01() { var text = @"namespace NS { public interface IGoo<T> { void M(T t); void M(ref T t); void M(out T t); } internal class CGoo { private struct SGoo { void M<T>(T t) { } void M<T>(ref T t) { } void M<T>(out T t) { } } public int RetInt(byte b, out int i) { return i; } public int RetInt(byte b, ref int j) { return 3; } public int RetInt(byte b, int k) { return 4; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,14): error CS0663: 'IGoo<T>' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' // void M(out T t); Diagnostic(ErrorCode.ERR_OverloadRefKind, "M").WithArguments("NS.IGoo<T>", "method", "out", "ref").WithLocation(7, 14), // (24,20): error CS0663: 'CGoo' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public int RetInt(byte b, ref int j) Diagnostic(ErrorCode.ERR_OverloadRefKind, "RetInt").WithArguments("NS.CGoo", "method", "ref", "out").WithLocation(24, 20), // (16,18): error CS0663: 'CGoo.SGoo' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' // void M<T>(out T t) { } Diagnostic(ErrorCode.ERR_OverloadRefKind, "M").WithArguments("NS.CGoo.SGoo", "method", "out", "ref").WithLocation(16, 18), // (21,20): error CS0269: Use of unassigned out parameter 'i' // return i; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "i").WithArguments("i").WithLocation(21, 20), // (21,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // return i; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return i;").WithArguments("i").WithLocation(21, 13), // (16,18): error CS0177: The out parameter 't' must be assigned to before control leaves the current method // void M<T>(out T t) { } Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("t").WithLocation(16, 18) ); } [Fact] public void CS0666ERR_ProtectedInStruct01() { var text = @"namespace NS { internal struct S1<T, V> { protected T field; protected internal void M(T t, V v) { } protected object P { get { return null; } } // Dev10 no error protected event System.Action E; struct S2 { protected void M1<X>(X p) { } protected internal R M2<X, R>(ref X p, R r) { return r; } protected internal object Q { get; set; } // Dev10 no error protected event System.Action E; } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,21): error CS0666: 'NS.S1<T, V>.field': new protected member declared in struct // protected T field; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("NS.S1<T, V>.field"), // (7,26): error CS0666: 'NS.S1<T, V>.P': new protected member declared in struct // protected object P { get { return null; } } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "P").WithArguments("NS.S1<T, V>.P"), // (8,39): error CS0666: 'NS.S1<T, V>.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.E"), // (6,33): error CS0666: 'NS.S1<T, V>.M(T, V)': new protected member declared in struct // protected internal void M(T t, V v) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M").WithArguments("NS.S1<T, V>.M(T, V)"), // (14,39): error CS0666: 'NS.S1<T, V>.S2.Q': new protected member declared in struct // protected internal object Q { get; set; } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Q").WithArguments("NS.S1<T, V>.S2.Q"), // (15,43): error CS0666: 'NS.S1<T, V>.S2.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.S2.E"), // (12,28): error CS0666: 'NS.S1<T, V>.S2.M1<X>(X)': new protected member declared in struct // protected void M1<X>(X p) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M1").WithArguments("NS.S1<T, V>.S2.M1<X>(X)"), // (13,34): error CS0666: 'NS.S1<T, V>.S2.M2<X, R>(ref X, R)': new protected member declared in struct // protected internal R M2<X, R>(ref X p, R r) { return r; } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M2").WithArguments("NS.S1<T, V>.S2.M2<X, R>(ref X, R)"), // (5,21): warning CS0649: Field 'NS.S1<T, V>.field' is never assigned to, and will always have its default value // protected T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.S1<T, V>.field", ""), // (8,39): warning CS0067: The event 'NS.S1<T, V>.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.E"), // (15,43): warning CS0067: The event 'NS.S1<T, V>.S2.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.S2.E") ); } [Fact] public void CS0666ERR_ProtectedInStruct02() { var text = @"struct S { protected object P { get { return null; } } public int Q { get; protected set; } } struct C<T> { protected internal T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 4, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 45 }); } [Fact] public void CS0666ERR_ProtectedInStruct03() { var text = @" struct S { protected event System.Action E; protected event System.Action F { add { } remove { } } protected int this[int x] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (4,35): error CS0666: 'S.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("S.E"), // (5,35): error CS0666: 'S.F': new protected member declared in struct // protected event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "F").WithArguments("S.F"), // (6,19): error CS0666: 'S.this[int]': new protected member declared in struct // protected int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "this").WithArguments("S.this[int]"), // (4,35): warning CS0067: The event 'S.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("S.E")); } [Fact] public void CS0668ERR_InconsistentIndexerNames() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { [IndexerName(""IName1"")] public int this[int index] // indexer declaration { get { return index; } set { } } [IndexerName(""IName2"")] public int this[string s] // CS0668, change IName2 to IName1 { get { return int.Parse(s); } set { } } void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InconsistentIndexerNames, Line = 19, Column = 16 }); } [Fact] public void CS0668ERR_InconsistentIndexerNames02() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { public int this[int[] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (12,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (15,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (18,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } /// <summary> /// Same as 02, but with an explicit interface implementation between each pair. /// </summary> [Fact] public void CS0668ERR_InconsistentIndexerNames03() { var text = @" using System.Runtime.CompilerServices; interface I { int this[int[] index] { get; set; } int this[int[,] index] { get; set; } int this[int[,,] index] { get; set; } int this[int[,,,] index] { get; set; } int this[int[,,,,] index] { get; set; } int this[int[,,,,,] index] { get; set; } } class IndexerClass : I { int I.this[int[] index] { get { return 0; } set { } } public int this[int[] index] { get { return 0; } set { } } int I.this[int[,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } int I.this[int[,,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } int I.this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } int I.this[int[,,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } int I.this[int[,,,,,] index] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (23,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (28,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (33,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (38,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact()] public void CS0669ERR_ComImportWithUserCtor() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""00000000-0000-0000-0000-000000000001"")] class TestClass { TestClass() // CS0669, delete constructor to resolve { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,5): error CS0669: A class with the ComImport attribute cannot have a user-defined constructor // TestClass() // CS0669, delete constructor to resolve Diagnostic(ErrorCode.ERR_ComImportWithUserCtor, "TestClass").WithLocation(5, 5)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType01() { var text = @"namespace NS { public class Goo { void Field2 = 0; public void Field1; public struct SGoo { void Field1; internal void Field2; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,9): error CS0670: Field cannot have void type // void Field2 = 0; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (6,16): error CS0670: Field cannot have void type // public void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (10,13): error CS0670: Field cannot have void type // void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (11,22): error CS0670: Field cannot have void type // internal void Field2; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (5,23): error CS0029: Cannot implicitly convert type 'int' to 'void' // void Field2 = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "void"), // (10,18): warning CS0169: The field 'NS.Goo.SGoo.Field1' is never used // void Field1; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("NS.Goo.SGoo.Field1"), // (11,27): warning CS0649: Field 'NS.Goo.SGoo.Field2' is never assigned to, and will always have its default value // internal void Field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("NS.Goo.SGoo.Field2", "") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0673ERR_SystemVoid01() { var source = @"namespace NS { using System; interface IGoo<T> { Void M(T t); } class Goo { extern Void GetVoid(); struct SGoo : IGoo<Void> { } } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo<Void>").WithArguments("NS.Goo.SGoo", "NS.IGoo<System.Void>.M(System.Void)"), Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "GetVoid").WithArguments("NS.Goo.GetVoid()")); } [Fact] public void CS0674ERR_ExplicitParamArray() { var text = @"using System; public class MyClass { public static void UseParams([ParamArray] int[] list) // CS0674 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitParamArray, Line = 4, Column = 35 }); } [Fact] public void CS0677ERR_VolatileStruct() { var text = @"class TestClass { private volatile long i; // CS0677 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,27): error CS0677: 'TestClass.i': a volatile field cannot be of the type 'long' // private volatile long i; // CS0677 Diagnostic(ErrorCode.ERR_VolatileStruct, "i").WithArguments("TestClass.i", "long"), // (3,27): warning CS0169: The field 'TestClass.i' is never used // private volatile long i; // CS0677 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i") ); } [Fact] public void CS0677ERR_VolatileStruct_TypeParameter() { var text = @" class C1<T> { volatile T f; // CS0677 } class C2<T> where T : class { volatile T f; } class C3<T> where T : struct { volatile T f; // CS0677 } class C4<T> where T : C1<int> { volatile T f; } interface I { } class C5<T> where T : I { volatile T f; // CS0677 } "; CreateCompilation(text).VerifyDiagnostics( // (4,16): error CS0677: 'C1<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C1<T>.f", "T"), // (14,16): error CS0677: 'C3<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C3<T>.f", "T"), // (26,16): error CS0677: 'C5<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C5<T>.f", "T"), // (4,16): warning CS0169: The field 'C1<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C1<T>.f"), // (9,16): warning CS0169: The field 'C2<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C2<T>.f"), // (14,16): warning CS0169: The field 'C3<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C3<T>.f"), // (19,16): warning CS0169: The field 'C4<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C4<T>.f"), // (26,16): warning CS0169: The field 'C5<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C5<T>.f")); } [Fact] public void CS0678ERR_VolatileAndReadonly() { var text = @"class TestClass { private readonly volatile int i; // CS0678 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,35): error CS0678: 'TestClass.i': a field cannot be both volatile and readonly // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.ERR_VolatileAndReadonly, "i").WithArguments("TestClass.i"), // (3,35): warning CS0169: The field 'TestClass.i' is never used // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i")); } [Fact] public void CS0681ERR_AbstractField01() { var text = @"namespace NS { class Goo<T> { public abstract T field; struct SGoo { abstract internal Goo<object> field; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,27): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // public abstract T field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (10,43): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract internal Goo<object> field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (6,27): warning CS0649: Field 'NS.Goo<T>.field' is never assigned to, and will always have its default value // public abstract T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Goo<T>.field", ""), // (10,43): warning CS0649: Field 'NS.Goo<T>.SGoo.field' is never assigned to, and will always have its default value null // abstract internal Goo<object> field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Goo<T>.SGoo.field", "null") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(546447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546447")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS0682ERR_BogusExplicitImpl() { var source1 = @".class interface public abstract I { .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void set_P(object& v) { } .property instance object P() { .get instance object I::get_P() .set instance void I::set_P(object& v) } .method public abstract virtual instance void add_E(class [mscorlib]System.Action v) { } .method public abstract virtual instance void remove_E(class [mscorlib]System.Action& v) { } .event [mscorlib]System.Action E { .addon instance void I::add_E(class [mscorlib]System.Action v); .removeon instance void I::remove_E(class [mscorlib]System.Action& v); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class C1 : I { object I.get_P() { return null; } void I.set_P(ref object v) { } void I.add_E(Action v) { } void I.remove_E(ref Action v) { } } class C2 : I { object I.P { get { return null; } set { } } event Action I.E { add { } remove { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (11,14): error CS0682: 'C2.I.P' cannot implement 'I.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "P").WithArguments("C2.I.P", "I.P").WithLocation(11, 14), // (16,20): error CS0682: 'C2.I.E' cannot implement 'I.E' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "E").WithArguments("C2.I.E", "I.E").WithLocation(16, 20)); } [Fact] public void CS0683ERR_ExplicitMethodImplAccessor() { var text = @"interface IExample { int Test { get; } } class CExample : IExample { int IExample.get_Test() { return 0; } // CS0683 int IExample.Test { get { return 0; } } // correct } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitMethodImplAccessor, Line = 8, Column = 18 }); } [Fact] public void CS0685ERR_ConditionalWithOutParam() { var text = @"namespace NS { using System.Diagnostics; class Test { [Conditional(""DEBUG"")] void Debug(out int i) // CS0685 { i = 1; } [Conditional(""TRACE"")] void Trace(ref string p1, out string p2) // CS0685 { p2 = p1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (7,10): error CS0685: Conditional member 'NS.Test.Debug(out int)' cannot have an out parameter // [Conditional("DEBUG")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("NS.Test.Debug(out int)").WithLocation(7, 10), // (13,10): error CS0685: Conditional member 'NS.Test.Trace(ref string, out string)' cannot have an out parameter // [Conditional("TRACE")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""TRACE"")").WithArguments("NS.Test.Trace(ref string, out string)").WithLocation(13, 10)); } [Fact] public void CS0686ERR_AccessorImplementingMethod() { var text = @"interface I { int get_P(); } class C : I { public int P { get { return 1; } // CS0686 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AccessorImplementingMethod, Line = 10, Column = 9 }); } [Fact] public void CS0689ERR_DerivingFromATyVar01() { var text = @"namespace NS { interface IGoo<T, V> : V { } internal class A<T> : T // CS0689 { protected struct S : T { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 7, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 9, Column = 30 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0692ERR_DuplicateTypeParameter() { var source = @"class C<T, T> where T : class { void M<U, V, U>() where U : new() { } }"; CreateCompilation(source).VerifyDiagnostics( // (1,12): error CS0692: Duplicate type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(1, 12), // (4,18): error CS0692: Duplicate type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 18)); } [Fact] public void CS0693WRN_TypeParameterSameAsOuterTypeParameter01() { var text = @"namespace NS { interface IGoo<T, V> { void M<T>(); } public struct S<T> { public class Outer<T, V> { class Inner<T> // CS0693 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 5, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 10, Column = 28, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 12, Column = 25, IsWarning = true }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0694ERR_TypeVariableSameAsParent01() { var text = @"namespace NS { interface IGoo { void M<M>(M m); // OK (constraint applies to types but not methods) } class C<C> { public struct S<T, S> { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): error CS0694: Type parameter 'C' has the same name as the containing type, or method // class C<C> Diagnostic(ErrorCode.ERR_TypeVariableSameAsParent, "C").WithArguments("C").WithLocation(8, 13), // (10,28): error CS0694: Type parameter 'S' has the same name as the containing type, or method // public struct S<T, S> Diagnostic(ErrorCode.ERR_TypeVariableSameAsParent, "S").WithArguments("S").WithLocation(10, 28) ); } [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations() { // Note: more detailed unification tests are in TypeUnificationTests.cs var text = @"interface I<T> { } class G1<T1, T2> : I<T1>, I<T2> { } // CS0695 class G2<T1, T2> : I<int>, I<T2> { } // CS0695 class G3<T1, T2> : I<int>, I<short> { } // fine class G4<T1, T2> : I<I<T1>>, I<T1> { } // fine class G5<T1, T2> : I<I<T1>>, I<T2> { } // CS0695 interface I2<T> : I<T> { } class G6<T1, T2> : I<T1>, I2<T2> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 3, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 5, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 11, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 15, Column = 7 }); } [WorkItem(539517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539517")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations2() { var text = @" interface I<T, S> { } class A<T, S> : I<I<T, T>, T>, I<I<T, S>, S> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 4, Column = 7 }); } [WorkItem(539518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539518")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations3() { var text = @" class A<T, S> { class B : A<B, B> { } interface IA { } interface IB : B.IA, B.B.IA { } // fine } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute01() { var text = @"class C<T> : System.Attribute { } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (1,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class C<T> : System.Attribute Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(1, 14)); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute02() { var text = @"class A : System.Attribute { } class B<T> : A { } class C<T> { class B : A { } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (2,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class B<T> : A { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "A").WithArguments("generic attributes").WithLocation(2, 14), // (5,15): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class B : A { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "A").WithArguments("generic attributes").WithLocation(5, 15)); } [Fact] public void CS0699ERR_TyVarNotFoundInConstraint() { var source = @"struct S<T> where T : class where U : struct { void M<U, V>() where T : new() where W : class { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0699: 'S<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "S<T>").WithLocation(3, 11), // (6,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'T' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "T").WithArguments("T", "S<T>.M<U, V>()").WithLocation(6, 15), // (7,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'W' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "W").WithArguments("W", "S<T>.M<U, V>()").WithLocation(7, 15)); } [Fact] public void CS0701ERR_BadBoundType() { var source = @"delegate void D(); enum E { } struct S { } sealed class A<T> { } class C { void M1<T>() where T : string { } void M2<T>() where T : D { } void M3<T>() where T : E { } void M4<T>() where T : S { } void M5<T>() where T : A<T> { } }"; CreateCompilation(source).VerifyDiagnostics( // (7,28): error CS0701: 'string' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "string").WithArguments("string").WithLocation(7, 28), // (8,28): error CS0701: 'D' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "D").WithArguments("D").WithLocation(8, 28), // (9,28): error CS0701: 'E' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "E").WithArguments("E").WithLocation(9, 28), // (10,28): error CS0701: 'S' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "S").WithArguments("S").WithLocation(10, 28), // (11,28): error CS0701: 'A<T>' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "A<T>").WithArguments("A<T>").WithLocation(11, 28)); } [Fact] public void CS0702ERR_SpecialTypeAsBound() { var source = @"using System; interface IA<T> where T : object { } interface IB<T> where T : System.Object { } interface IC<T, U> where T : ValueType { } interface ID<T> where T : Array { }"; CreateCompilation(source).VerifyDiagnostics( // (2,27): error CS0702: Constraint cannot be special class 'object' // interface IA<T> where T : object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(2, 27), // (3,27): error CS0702: Constraint cannot be special class 'object' // interface IB<T> where T : System.Object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object").WithArguments("object").WithLocation(3, 27), // (4,30): error CS0702: Constraint cannot be special class 'System.ValueType' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "ValueType").WithArguments("System.ValueType").WithLocation(4, 30), // (5,27): error CS0702: Constraint cannot be special class 'System.Array' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "Array").WithArguments("System.Array").WithLocation(5, 27)); } [Fact] public void CS07ERR_BadVisBound01() { var source = @"public class C1 { protected interface I<T> { } internal class A<T> { } public delegate void D<T>() where T : A<T>, I<T>; } public class C2 : C1 { protected struct S<T, U, V> where T : I<A<T>> where U : I<I<U>> where V : A<A<V>> { } internal void M<T, U, V>() where T : A<I<T>> where U : I<I<U>> where V : A<A<V>> { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,43): error CS07: Inconsistent accessibility: constraint type 'C1.A<T>' is less accessible than 'C1.D<T>' // public delegate void D<T>() where T : A<T>, I<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "A<T>").WithArguments("C1.D<T>", "C1.A<T>").WithLocation(5, 43), // (5,49): error CS07: Inconsistent accessibility: constraint type 'C1.I<T>' is less accessible than 'C1.D<T>' // public delegate void D<T>() where T : A<T>, I<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "I<T>").WithArguments("C1.D<T>", "C1.I<T>").WithLocation(5, 49), // (14,19): error CS07: Inconsistent accessibility: constraint type 'C1.A<C1.I<T>>' is less accessible than 'C2.M<T, U, V>()' // where T : A<I<T>> Diagnostic(ErrorCode.ERR_BadVisBound, "A<I<T>>").WithArguments("C2.M<T, U, V>()", "C1.A<C1.I<T>>").WithLocation(14, 19), // (15,19): error CS07: Inconsistent accessibility: constraint type 'C1.I<C1.I<U>>' is less accessible than 'C2.M<T, U, V>()' // where U : I<I<U>> Diagnostic(ErrorCode.ERR_BadVisBound, "I<I<U>>").WithArguments("C2.M<T, U, V>()", "C1.I<C1.I<U>>").WithLocation(15, 19), // (10,19): error CS07: Inconsistent accessibility: constraint type 'C1.I<C1.A<T>>' is less accessible than 'C2.S<T, U, V>' // where T : I<A<T>> Diagnostic(ErrorCode.ERR_BadVisBound, "I<A<T>>").WithArguments("C2.S<T, U, V>", "C1.I<C1.A<T>>").WithLocation(10, 19), // (12,19): error CS07: Inconsistent accessibility: constraint type 'C1.A<C1.A<V>>' is less accessible than 'C2.S<T, U, V>' // where V : A<A<V>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "A<A<V>>").WithArguments("C2.S<T, U, V>", "C1.A<C1.A<V>>").WithLocation(12, 19)); } [Fact] public void CS07ERR_BadVisBound02() { var source = @"internal interface IA<T> { } public interface IB<T, U> { } public class A { public partial class B<T, U> { } public partial class B<T, U> where U : IB<U, IA<T>> { } public partial class B<T, U> where U : IB<U, IA<T>> { } } public partial class C { public partial void M<T>() where T : IA<T>; public partial void M<T>() where T : IA<T> { } }"; CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (6,44): error CS07: Inconsistent accessibility: constraint type 'IB<U, IA<T>>' is less accessible than 'A.B<T, U>' // public partial class B<T, U> where U : IB<U, IA<T>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IB<U, IA<T>>").WithArguments("A.B<T, U>", "IB<U, IA<T>>").WithLocation(6, 44), // (7,44): error CS07: Inconsistent accessibility: constraint type 'IB<U, IA<T>>' is less accessible than 'A.B<T, U>' // public partial class B<T, U> where U : IB<U, IA<T>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IB<U, IA<T>>").WithArguments("A.B<T, U>", "IB<U, IA<T>>").WithLocation(7, 44), // (11,42): error CS07: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' // public partial void M<T>() where T : IA<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "IA<T>").WithArguments("C.M<T>()", "IA<T>").WithLocation(11, 42), // (12,42): error CS07: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' // public partial void M<T>() where T : IA<T> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IA<T>").WithArguments("C.M<T>()", "IA<T>").WithLocation(12, 42)); } [Fact] public void CS0708ERR_InstanceMemberInStaticClass01() { var text = @"namespace NS { public static class Goo { int i; void M() { } internal object P { get; set; } event System.Action E; } static class Bar<T> { T field; T M(T x) { return x; } int Q { get { return 0; } } event System.Action<T> E; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,13): error CS0708: 'NS.Goo.i': cannot declare instance members in a static class // int i; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "i").WithArguments("NS.Goo.i"), // (7,25): error CS0708: 'NS.Goo.P': cannot declare instance members in a static class // internal object P { get; set; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "P").WithArguments("NS.Goo.P"), // (8,29): error CS0708: 'E': cannot declare instance members in a static class // event System.Action E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (6,14): error CS0708: 'M': cannot declare instance members in a static class // void M() { } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (13,11): error CS0708: 'NS.Bar<T>.field': cannot declare instance members in a static class // T field; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "field").WithArguments("NS.Bar<T>.field"), // (15,13): error CS0708: 'NS.Bar<T>.Q': cannot declare instance members in a static class // int Q { get { return 0; } } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "Q").WithArguments("NS.Bar<T>.Q"), // (16,32): error CS0708: 'E': cannot declare instance members in a static class // event System.Action<T> E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (16,32): warning CS0067: The event 'NS.Bar<T>.E' is never used // event System.Action<T> E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Bar<T>.E"), // (8,29): warning CS0067: The event 'NS.Goo.E' is never used // event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Goo.E"), // (14,11): error CS0708: 'M': cannot declare instance members in a static class // T M(T x) { return x; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (5,13): warning CS0169: The field 'NS.Goo.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("NS.Goo.i"), // (13,11): warning CS0169: The field 'NS.Bar<T>.field' is never used // T field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Bar<T>.field")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0709ERR_StaticBaseClass01() { var text = @"namespace NS { public static class Base { } public class Derived : Base { } static class Base1<T, V> { } sealed class Seal<T> : Base1<T, short> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 7, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 15, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0710ERR_ConstructorInStaticClass01() { var text = @"namespace NS { public static class C { public C() {} C(string s) { } static class D<T, V> { internal D() { } internal D(params sbyte[] ary) { } } static C() { } // no error } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 10, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 11, Column = 22 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0711ERR_DestructorInStaticClass() { var text = @"public static class C { ~C() // CS0711 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DestructorInStaticClass, Line = 3, Column = 6 }); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" static class C { static void Main() { C c = new C(); //CS0712 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS07: Cannot declare a variable of static type 'C' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "C").WithArguments("C"), // (6,15): error CS0712: Cannot create an instance of the static class 'C' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new C()").WithArguments("C")); } [Fact] public void CS07ERR_StaticDerivedFromNonObject01() { var source = @"namespace NS { public class Base { } public static class Derived : Base { } class Base1<T, V> { } static class D<V> : Base1<string, V> { } } "; CreateCompilation(source).VerifyDiagnostics( // (75): error CS07: Static class 'Derived' cannot derive from type 'Base'. Static classes must derive from object. // public static class Derived : Base Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Base").WithArguments("NS.Derived", "NS.Base").WithLocation(7, 35), // (15,25): error CS07: Static class 'D<V>' cannot derive from type 'Base1<string, V>'. Static classes must derive from object. // static class D<V> : Base1<string, V> Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Base1<string, V>").WithArguments("NS.D<V>", "NS.Base1<string, V>").WithLocation(15, 25)); } [Fact] public void CS07ERR_StaticDerivedFromNonObject02() { var source = @"delegate void A(); struct B { } static class C : A { } static class D : B { } "; CreateCompilation(source).VerifyDiagnostics( // (4,18): error CS07: Static class 'D' cannot derive from type 'B'. Static classes must derive from object. // static class D : B { } Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "B").WithArguments("D", "B").WithLocation(4, 18), // (3,18): error CS07: Static class 'C' cannot derive from type 'A'. Static classes must derive from object. // static class C : A { } Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "A").WithArguments("C", "A").WithLocation(3, 18)); } [Fact] public void CS0714ERR_StaticClassInterfaceImpl01() { var text = @"namespace NS { interface I { } public static class C : I { } interface IGoo<T, V> { } static class D<V> : IGoo<string, V> { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,29): error CS0714: 'NS.C': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "I").WithArguments("NS.C", "NS.I"), // (15,25): error CS0714: 'NS.D<V>': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "IGoo<string, V>").WithArguments("NS.D<V>", "NS.IGoo<string, V>")); } [Fact] public void CS0715ERR_OperatorInStaticClass() { var text = @" public static class C { public static C operator +(C c) // CS0715 { return c; } } "; // Note that Roslyn produces these three errors. The native compiler // produces only the first. We might consider suppressing the additional // "cascading" errors in Roslyn. CreateCompilation(text).VerifyDiagnostics( // (4,30): error CS0715: 'C.operator +(C)': static classes cannot contain user-defined operators // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_OperatorInStaticClass, "+").WithArguments("C.operator +(C)"), // (4,30): error CS0721: 'C': static types cannot be used as parameters // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "+").WithArguments("C"), // (4,19): error CS0722: 'C': static types cannot be used as return types // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "C").WithArguments("C") ); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" static class C { static void M(object o) { M((C)o); M((C)new object()); M((C)null); M((C)1); M((C)""a""); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)o").WithArguments("C"), // (7,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)new object()").WithArguments("C"), // (8,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)null").WithArguments("C"), // (9,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)1").WithArguments("C"), // (10,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)\"a\"").WithArguments("C")); } [Fact] public void CS7023ERR_StaticInIsAsOrIs() { // The C# specification states that it is always illegal // to use a static type with "is" and "as". The native // compiler allows it in some cases; Roslyn gives a warning // at level '/warn:5' or higher. var text = @" static class C { static void M(object o) { M(o as C); // legal in native M(new object() as C); // legal in native M(null as C); // legal in native M(1 as C); M(""a"" as C); M(o is C); // legal in native, no warning M(new object() is C); // legal in native, no warning M(null is C); // legal in native, warns M(1 is C); // legal in native, warns M(""a"" is C); // legal in native, warns } } "; var strictDiagnostics = new[] { // (6,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(o as C); // legal in native Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "o as C").WithArguments("C").WithLocation(6, 11), // (7,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(new object() as C); // legal in native Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "new object() as C").WithArguments("C").WithLocation(7, 11), // (8,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(null as C); // legal in native Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "null as C").WithArguments("C").WithLocation(8, 11), // (9,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(1 as C); Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "1 as C").WithArguments("C").WithLocation(9, 11), // (9,11): error CS0039: Cannot convert type 'int' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M(1 as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "1 as C").WithArguments("int", "C").WithLocation(9, 11), // (10,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M("a" as C); Diagnostic(ErrorCode.WRN_StaticInAsOrIs, @"""a"" as C").WithArguments("C").WithLocation(10, 11), // (10,11): error CS0039: Cannot convert type 'string' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M("a" as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"""a"" as C").WithArguments("string", "C").WithLocation(10, 11), // (12,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(o is C); // legal in native, no warning Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "o is C").WithArguments("C").WithLocation(12, 11), // (13,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(new object() is C); // legal in native, no warning Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "new object() is C").WithArguments("C").WithLocation(13, 11), // (14,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(null is C); // legal in native, warns Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "null is C").WithArguments("C").WithLocation(14, 11), // (14,11): warning CS0184: The given expression is never of the provided ('C') type // M(null is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is C").WithArguments("C").WithLocation(14, 11), // (15,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(1 is C); // legal in native, warns Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "1 is C").WithArguments("C").WithLocation(15, 11), // (15,11): warning CS0184: The given expression is never of the provided ('C') type // M(1 is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is C").WithArguments("C").WithLocation(15, 11), // (16,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M("a" is C); // legal in native, warns Diagnostic(ErrorCode.WRN_StaticInAsOrIs, @"""a"" is C").WithArguments("C").WithLocation(16, 11), // (16,11): warning CS0184: The given expression is never of the provided ('C') type // M("a" is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, @"""a"" is C").WithArguments("C").WithLocation(16, 11) }; // in /warn:5 we diagnose "is" and "as" operators with a static type. var strictComp = CreateCompilation(text); strictComp.VerifyDiagnostics(strictDiagnostics); // these rest of the diagnostics correspond to those produced by the native compiler. var regularDiagnostics = strictDiagnostics.Where(d => !d.Code.Equals((int)ErrorCode.WRN_StaticInAsOrIs)).ToArray(); var regularComp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(4)); regularComp.VerifyDiagnostics(regularDiagnostics); } [Fact] public void CS0717ERR_ConstraintIsStaticClass() { var source = @"static class A { } class B { internal static class C { } } delegate void D<T, U>() where T : A where U : B.C;"; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS0717: 'A': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "A").WithArguments("A").WithLocation(4, 15), // (5,15): error CS0717: 'B.C': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "B.C").WithArguments("B.C").WithLocation(5, 15)); } [Fact] public void CS0718ERR_GenericArgIsStaticClass01() { var text = @"interface I<T> { } class C<T> { internal static void M() { } } static class S { static void M<T>() { I<S> i = null; C<S> c = null; C<S>.M(); M<S>(); object o = typeof(I<S>); } }"; CreateCompilation(text).VerifyDiagnostics( // (10,11): error CS0718: 'S': static types cannot be used as type arguments // I<S> i = null; Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(10, 11), // (11,11): error CS0718: 'S': static types cannot be used as type arguments // C<S> c = null; Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(11, 11), // (12,11): error CS0718: 'S': static types cannot be used as type arguments // C<S>.M(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(12, 11), // (13,9): error CS0718: 'S': static types cannot be used as type arguments // M<S>(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "M<S>").WithArguments("S").WithLocation(13, 9), // (14,29): error CS0718: 'S': static types cannot be used as type arguments // object o = typeof(I<S>); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(14, 29), // (10,14): warning CS0219: The variable 'i' is assigned but its value is never used // I<S> i = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(10, 14), // (11,14): warning CS0219: The variable 'c' is assigned but its value is never used // C<S> c = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(11, 14) ); } [Fact] public void CS0719ERR_ArrayOfStaticClass01() { var text = @"namespace NS { public static class C { } static class D<T> { } class Test { public static int Main() { var ca = new C[] { null }; var cd = new D<long>[9]; return 1; } } } "; // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a local because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 14, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 15, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void ERR_VarDeclIsStaticClass02() { // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a field because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var text = @"namespace NS { public static class C { } static class D<T> { } class Test { C[] X; C Y; D<int> Z; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,9): error CS0719: 'NS.C': array elements cannot be of static type // C[] X; Diagnostic(ErrorCode.ERR_ArrayOfStaticClass, "C").WithArguments("NS.C"), // (13,11): error CS07: Cannot declare a variable of static type 'NS.C' // C Y; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Y").WithArguments("NS.C"), // (14,16): error CS07: Cannot declare a variable of static type 'NS.D<int>' // D<int> Z; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Z").WithArguments("NS.D<int>"), // (12,13): warning CS0169: The field 'NS.Test.X' is never used // C[] X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("NS.Test.X"), // (13,11): warning CS0169: The field 'NS.Test.Y' is never used // C Y; Diagnostic(ErrorCode.WRN_UnreferencedField, "Y").WithArguments("NS.Test.Y"), // (14,16): warning CS0169: The field 'NS.Test.Z' is never used // D<int> Z; Diagnostic(ErrorCode.WRN_UnreferencedField, "Z").WithArguments("NS.Test.Z")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0720ERR_IndexerInStaticClass() { var text = @"public static class Test { public int this[int index] // CS0720 { get { return 1; } set {} } static void Main() {} } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerInStaticClass, Line = 3, Column = 16 }); } [Fact] public void CS0721ERR_ParameterIsStaticClass01() { var text = @"namespace NS { public static class C { } public static class D<T> { } interface IGoo<T> { void M(D<T> d); // Dev10 no error? } class Test { public void F(C p) // CS0721 { } struct S { object M<T>(D<T> p1) // CS0721 { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ParameterIsStaticClass, Line = 12, Column = 14, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 16, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 22, Column = 20 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0721ERR_ParameterIsStaticClass02() { var source = @"static class S { } class C { S P { set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(4, 11)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass01() { var source = @"namespace NS { public static class C { } public static class D<T> { } interface IGoo<T> { D<T> M(); // Dev10 no error? } class Test { extern public C F(); // CS0722 // { // return default(C); // } struct S { extern D<sbyte> M(); // CS0722 // { // return default(D<sbyte>); // } } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,14): warning CS8898: 'NS.D<T>': static types cannot be used as return types Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "M").WithArguments("NS.D<T>").WithLocation(12, 14), // (16,25): error CS0722: 'NS.C': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("NS.C").WithLocation(16, 25), // (23,29): error CS0722: 'NS.D<sbyte>': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "M").WithArguments("NS.D<sbyte>").WithLocation(23, 29), // (16,25): warning CS0626: Method, operator, or accessor 'NS.Test.F()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "F").WithArguments("NS.Test.F()").WithLocation(16, 25), // (23,29): warning CS0626: Method, operator, or accessor 'NS.Test.S.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.S.M()").WithLocation(23, 29)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass02() { var source = @"static class S { } class C { S P { get { return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(4, 11)); } [WorkItem(530434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530434")] [Fact(Skip = "530434")] public void CS0722ERR_ReturnTypeIsStaticClass03() { var source = @"static class S { } class C { public abstract S F(); public abstract S P { get; } public abstract S Q { set; } }"; CreateCompilation(source).VerifyDiagnostics( // (4,23): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("S").WithLocation(4, 23), // (4,23): error CS0513: 'C.F()' is abstract but it is contained in non-abstract type 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "F").WithArguments("C.F()", "C").WithLocation(4, 23), // (5,27): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract type 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.P.get", "C").WithLocation(5, 27), // (6,27): error CS0513: 'C.Q.set' is abstract but it is contained in non-abstract type 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.Q.set", "C").WithLocation(6, 27), // (5,27): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(5, 27), // (6,27): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(6, 27)); } [WorkItem(546540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546540")] [Fact] public void CS0722ERR_ReturnTypeIsStaticClass04() { var source = @"static class S1 { } static class S2 { } class C { public static S1 operator-(C c) { return null; } public static implicit operator S2(C c) { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (5,19): error CS0722: 'S1': static types cannot be used as return types // public static S1 operator-(C c) Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S1").WithArguments("S1"), // (9,37): error CS0722: 'S2': static types cannot be used as return types // public static implicit operator S2(C c) { return null; } Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S2").WithArguments("S2") ); } [Fact] public void CS0729ERR_ForwardedTypeInThisAssembly() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Test))] public class Test { } "; CreateCompilation(csharp).VerifyDiagnostics( // (4,12): error CS0729: Type 'Test' is defined in this assembly, but a type forwarder is specified for it // [assembly: TypeForwardedTo(typeof(Test))] Diagnostic(ErrorCode.ERR_ForwardedTypeInThisAssembly, "TypeForwardedTo(typeof(Test))").WithArguments("Test")); } [Fact, WorkItem(38256, "https://github.com/dotnet/roslyn/issues/38256")] public void ParameterAndReturnTypesAreStaticClassesWarning() { var source = @" static class C {} interface I { void M1(C c); // 1 C M2(); // 2 C Prop { get; set; } // 3, 4 C this[C c] { get; set; } // 5, 6, 7 } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,10): warning CS8897: 'C': static types cannot be used as parameters // void M1(C c); // 1 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "M1").WithArguments("C").WithLocation(5, 10), // (6,7): warning CS8898: 'C': static types cannot be used as return types // C M2(); // 2 Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "M2").WithArguments("C").WithLocation(6, 7), // (7,14): warning CS8898: 'C': static types cannot be used as return types // C Prop { get; set; } // 3, 4 Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "get").WithArguments("C").WithLocation(7, 14), // (7,19): warning CS8897: 'C': static types cannot be used as parameters // C Prop { get; set; } // 3, 4 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "set").WithArguments("C").WithLocation(7, 19), // (8,7): warning CS8897: 'C': static types cannot be used as parameters // C this[C c] { get; set; } // 5, 6, 7 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "this").WithArguments("C").WithLocation(8, 7), // (8,19): warning CS8898: 'C': static types cannot be used as return types // C this[C c] { get; set; } // 5, 6, 7 Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "get").WithArguments("C").WithLocation(8, 19), // (8,24): warning CS8897: 'C': static types cannot be used as parameters // C this[C c] { get; set; } // 5, 6, 7 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "set").WithArguments("C").WithLocation(8, 24) ); comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(4)); comp.VerifyDiagnostics(); } [Fact] public void CS0730ERR_ForwardedTypeIsNested() { var text1 = @"public class C { public class CC { } } "; var text2 = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(C.CC))]"; var comp1 = CreateCompilation(text1); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilation(text2, new MetadataReference[] { compRef1 }); comp2.VerifyDiagnostics( // (4,12): error CS0730: Cannot forward type 'C.CC' because it is a nested type of 'C' // [assembly: TypeForwardedTo(typeof(C.CC))] Diagnostic(ErrorCode.ERR_ForwardedTypeIsNested, "TypeForwardedTo(typeof(C.CC))").WithArguments("C.CC", "C")); } // See TypeForwarders.Cycle1, etc. //[Fact] //public void CS0731ERR_CycleInTypeForwarder() [Fact] public void CS0735ERR_InvalidFwdType() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(string[]))] [assembly: TypeForwardedTo(typeof(System.Int32*))] "; CreateCompilation(csharp).VerifyDiagnostics( // (4,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(string[]))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(string[]))"), // (5,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(System.Int32*))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(System.Int32*))")); } [Fact] public void CS0736ERR_CloseUnimplementedInterfaceMemberStatic() { var text = @"namespace CS0736 { interface ITest { int testMethod(int x); } class Program : ITest // CS0736 { public static int testMethod(int x) { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 8, Column = 21 }); } [Fact] public void CS0737ERR_CloseUnimplementedInterfaceMemberNotPublic() { var text = @"interface ITest { int Return42(); } struct Struct1 : ITest // CS0737 { int Return42() { return (42); } } public class Test { public static void Main(string[] args) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 6, Column = 18 }); } [Fact] public void CS0738ERR_CloseUnimplementedInterfaceMemberWrongReturnType() { var text = @" interface ITest { int TestMethod(); } public class Test : ITest { public void TestMethod() { } // CS0738 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 7, Column = 21 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_1() { var text = @"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] namespace cs0739 { class Program { static void Main(string[] args) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateTypeForwarder, Line = 2, Column = 12 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_2() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(System.Int32))] [assembly: TypeForwardedTo(typeof(int))] [assembly: TypeForwardedTo(typeof(List<string>))] [assembly: TypeForwardedTo(typeof(List<System.String>))] "; CreateCompilation(csharp).VerifyDiagnostics( // (6,12): error CS0739: 'int' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(int))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(int))").WithArguments("int"), // (9,12): error CS0739: 'System.Collections.Generic.List<string>' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(List<System.String>))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(List<System.String>))").WithArguments("System.Collections.Generic.List<string>")); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_3() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(List<int>))] [assembly: TypeForwardedTo(typeof(List<char>))] [assembly: TypeForwardedTo(typeof(List<>))] "; CreateCompilation(csharp).VerifyDiagnostics(); } [Fact] public void CS0750ERR_PartialMethodInvalidModifier() { var text = @" public class Base { protected virtual void PartG() { } protected void PartH() { } protected virtual void PartI() { } } public partial class C : Base { public partial void PartA(); private partial void PartB(); protected partial void PartC(); internal partial void PartD(); virtual partial void PartE(); abstract partial void PartF(); override partial void PartG(); new partial void PartH(); sealed override partial void PartI(); [System.Runtime.InteropServices.DllImport(""none"")] extern partial void PartJ(); public static int Main() { return 1; } } "; CreateCompilation(text, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (19,25): error CS8793: Partial method 'C.PartA()' must have an implementation part because it has accessibility modifiers. // public partial void PartA(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartA").WithArguments("C.PartA()").WithLocation(19, 25), // (20,26): error CS8793: Partial method 'C.PartB()' must have an implementation part because it has accessibility modifiers. // private partial void PartB(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartB").WithArguments("C.PartB()").WithLocation(20, 26), // (21,28): error CS8793: Partial method 'C.PartC()' must have an implementation part because it has accessibility modifiers. // protected partial void PartC(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartC").WithArguments("C.PartC()").WithLocation(21, 28), // (22,27): error CS8793: Partial method 'C.PartD()' must have an implementation part because it has accessibility modifiers. // internal partial void PartD(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartD").WithArguments("C.PartD()").WithLocation(22, 27), // (29,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.PartJ()' // extern partial void PartJ(); Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "PartJ").WithArguments("C.PartJ()").WithLocation(29, 25), // (23,26): error CS8796: Partial method 'C.PartE()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // virtual partial void PartE(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartE").WithArguments("C.PartE()").WithLocation(23, 26), // (24,27): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void PartF(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartF").WithLocation(24, 27), // (25,27): error CS8796: Partial method 'C.PartG()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // override partial void PartG(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartG").WithArguments("C.PartG()").WithLocation(25, 27), // (26,22): error CS8796: Partial method 'C.PartH()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // new partial void PartH(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartH").WithArguments("C.PartH()").WithLocation(26, 22), // (27,34): error CS8796: Partial method 'C.PartI()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // sealed override partial void PartI(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartI").WithArguments("C.PartI()").WithLocation(27, 34), // (29,25): error CS8796: Partial method 'C.PartJ()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // extern partial void PartJ(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartJ").WithArguments("C.PartJ()").WithLocation(29, 25), // (25,27): error CS0507: 'C.PartG()': cannot change access modifiers when overriding 'protected' inherited member 'Base.PartG()' // override partial void PartG(); Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "PartG").WithArguments("C.PartG()", "protected", "Base.PartG()").WithLocation(25, 27), // (27,34): error CS0507: 'C.PartI()': cannot change access modifiers when overriding 'protected' inherited member 'Base.PartI()' // sealed override partial void PartI(); Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "PartI").WithArguments("C.PartI()", "protected", "Base.PartI()").WithLocation(27, 34), // (28,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [System.Runtime.InteropServices.DllImport("none")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "System.Runtime.InteropServices.DllImport").WithLocation(28, 6)); } [Fact] public void CS0751ERR_PartialMethodOnlyInPartialClass() { var text = @" public class C { partial void Part(); // CS0751 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyInPartialClass, Line = 5, Column = 18 }); } [Fact] public void CS0752ERR_PartialMethodCannotHaveOutParameters() { var text = @" namespace NS { public partial class C { partial void F(out int x); } } "; CreateCompilation(text, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (7,22): error CS8795: Partial method 'C.F(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void F(out int x); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "F").WithArguments("NS.C.F(out int)").WithLocation(7, 22)); } [Fact] public void CS067ERR_ERR_PartialMisplaced() { var text = @" partial class C { partial int f; partial object P { get { return null; } } partial int this[int index] { get { return index; } } partial void M(); } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial int f; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(4, 5), // (5,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial object P { get { return null; } } Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(5, 5), // (6,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial int this[int index] Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(6, 5), // (4,17): warning CS0169: The field 'C.f' is never used // partial int f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C.f").WithLocation(4, 17)); } [Fact] public void CS0754ERR_PartialMethodNotExplicit() { var text = @" public interface IF { void Part(); } public partial class C : IF { partial void IF.Part(); //CS0754 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodNotExplicit, Line = 8, Column = 21 }); } [Fact] public void CS0755ERR_PartialMethodExtensionDifference() { var text = @"static partial class C { static partial void M1(this object o); static partial void M1(object o) { } static partial void M2(object o) { } static partial void M2(this object o); }"; CreateCompilation(text).VerifyDiagnostics( // (4,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M1").WithLocation(4, 25), // (5,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0756ERR_PartialMethodOnlyOneLatent() { var text = @" public partial class C { partial void Part(); partial void Part(); // CS0756 public static int Main() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0756: A partial method may not have multiple defining declarations // partial void Part(); // CS0756 Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "Part").WithLocation(5, 18), // (5,18): error CS0111: Type 'C' already defines a member called 'Part' with the same parameter types // partial void Part(); // CS0756 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Part").WithArguments("Part", "C").WithLocation(5, 18)); } [Fact] public void CS0757ERR_PartialMethodOnlyOneActual() { var text = @" public partial class C { partial void Part(); partial void Part() { } partial void Part() // CS0757 { } public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyOneActual, Line = 8, Column = 18 }); } [Fact] public void CS0758ERR_PartialMethodParamsDifference() { var text = @"partial class C { partial void M1(params object[] args); partial void M1(object[] args) { } partial void M2(int n, params object[] args) { } partial void M2(int n, object[] args); }"; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M1").WithLocation(4, 18), // (5,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M2").WithLocation(5, 18)); } [Fact] public void CS0759ERR_PartialMethodMustHaveLatent() { var text = @"partial class C { partial void M1() { } partial void M2(); }"; CreateCompilation(text).VerifyDiagnostics( // (3,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M1()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M1").WithArguments("C.M1()").WithLocation(3, 18)); } [WorkItem(5427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/5427")] [Fact] public void CS0759ERR_PartialMethodMustHaveLatent_02() { var text = @"using System; static partial class EExtensionMethod { static partial void M(this Array a); } static partial class EExtensionMethod { static partial void M() { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,25): error CS0759: No defining declaration found for implementing declaration of partial method'EExtensionMethod.M()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("EExtensionMethod.M()").WithLocation(9, 25)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints01() { var source = @"interface IA<T> { } interface IB { } partial class C<X> { // Different constraints: partial void A1<T>() where T : struct; partial void A2<T, U>() where T : struct where U : IA<T>; partial void A3<T>() where T : IA<T>; partial void A4<T, U>() where T : struct, IA<T>; // Additional constraints: partial void B1<T>(); partial void B2<T>() where T : X, new(); partial void B3<T, U>() where T : IA<T>; // Missing constraints. partial void C1<T>() where T : class; partial void C2<T>() where T : class, new(); partial void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. partial void D1<T>() where T : IA<T>, IB { } partial void D2<T, U, V>() where V : T, U, X { } // Different constraint clauses. partial void E1<T, U>() where U : T { } // Additional constraint clause. partial void F1<T, U>() where T : class { } // Missing constraint clause. partial void G1<T, U>() where T : class where U : T { } // Same constraint clauses, different order. partial void H1<T, U>() where T : class where U : T { } partial void H2<T, U>() where T : class where U : T { } partial void H3<T, U, V>() where V : class where U : IB where T : IA<V> { } // Different type parameter names. partial void K1<T, U>() where T : class where U : IA<T> { } partial void K2<T, U>() where T : class where U : T, IA<U> { } } partial class C<X> { // Different constraints: partial void A1<T>() where T : class { } partial void A2<T, U>() where T : struct where U : IB { } partial void A3<T>() where T : IA<IA<T>> { } partial void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: partial void B1<T>() where T : new() { } partial void B2<T>() where T : class, X, new() { } partial void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. partial void C1<T>() { } partial void C2<T>() where T : class { } partial void C3<T, U>() where U : IA<T> { } // Same constraints, different order. partial void D1<T>() where T : IB, IA<T>; partial void D2<T, U, V>() where V : U, X, T; // Different constraint clauses. partial void E1<T, U>() where T : class; // Additional constraint clause. partial void F1<T, U>() where T : class where U : T; // Missing constraint clause. partial void G1<T, U>() where T : class; // Same constraint clauses, different order. partial void H1<T, U>() where U : T where T : class; partial void H2<T, U>() where U : class where T : U; partial void H3<T, U, V>() where T : IA<V> where U : IB where V : class; // Different type parameter names. partial void K1<U, T>() where T : class where U : IA<T>; partial void K2<T1, T2>() where T1 : class where T2 : T1, IA<T2>; }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilation(source).VerifyDiagnostics( // (39,18): error CS0761: Partial method declarations of 'C<X>.A2<T, U>()' have inconsistent constraints for type parameter 'U' // partial void A2<T, U>() where T : struct where U : IB { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A2").WithArguments("C<X>.A2<T, U>()", "U").WithLocation(39, 18), // (40,18): error CS0761: Partial method declarations of 'C<X>.A3<T>()' have inconsistent constraints for type parameter 'T' // partial void A3<T>() where T : IA<IA<T>> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A3").WithArguments("C<X>.A3<T>()", "T").WithLocation(40, 18), // (41,18): error CS0761: Partial method declarations of 'C<X>.A4<T, U>()' have inconsistent constraints for type parameter 'T' // partial void A4<T, U>() where T : struct, IA<U> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A4").WithArguments("C<X>.A4<T, U>()", "T").WithLocation(41, 18), // (43,18): error CS0761: Partial method declarations of 'C<X>.B1<T>()' have inconsistent constraints for type parameter 'T' // partial void B1<T>() where T : new() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B1").WithArguments("C<X>.B1<T>()", "T").WithLocation(43, 18), // (44,18): error CS0761: Partial method declarations of 'C<X>.B2<T>()' have inconsistent constraints for type parameter 'T' // partial void B2<T>() where T : class, X, new() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B2").WithArguments("C<X>.B2<T>()", "T").WithLocation(44, 18), // (45,18): error CS0761: Partial method declarations of 'C<X>.B3<T, U>()' have inconsistent constraints for type parameter 'T' // partial void B3<T, U>() where T : IB, IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B3").WithArguments("C<X>.B3<T, U>()", "T").WithLocation(45, 18), // (47,18): error CS0761: Partial method declarations of 'C<X>.C1<T>()' have inconsistent constraints for type parameter 'T' // partial void C1<T>() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C1").WithArguments("C<X>.C1<T>()", "T").WithLocation(47, 18), // (48,18): error CS0761: Partial method declarations of 'C<X>.C2<T>()' have inconsistent constraints for type parameter 'T' // partial void C2<T>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C2").WithArguments("C<X>.C2<T>()", "T").WithLocation(48, 18), // (49,18): error CS0761: Partial method declarations of 'C<X>.C3<T, U>()' have inconsistent constraints for type parameter 'U' // partial void C3<T, U>() where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C3").WithArguments("C<X>.C3<T, U>()", "U").WithLocation(49, 18), // (22,18): error CS0761: Partial method declarations of 'C<X>.E1<T, U>()' have inconsistent constraints for type parameter 'T' // partial void E1<T, U>() where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "E1").WithArguments("C<X>.E1<T, U>()", "T").WithLocation(22, 18), // (22,18): error CS0761: Partial method declarations of 'C<X>.E1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void E1<T, U>() where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "E1").WithArguments("C<X>.E1<T, U>()", "U").WithLocation(22, 18), // (24,18): error CS0761: Partial method declarations of 'C<X>.F1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void F1<T, U>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "F1").WithArguments("C<X>.F1<T, U>()", "U").WithLocation(24, 18), // (26,18): error CS0761: Partial method declarations of 'C<X>.G1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void G1<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "G1").WithArguments("C<X>.G1<T, U>()", "U").WithLocation(26, 18), // (29,18): error CS0761: Partial method declarations of 'C<X>.H2<T, U>()' have inconsistent constraints for type parameter 'T' // partial void H2<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "H2").WithArguments("C<X>.H2<T, U>()", "T").WithLocation(29, 18), // (29,18): error CS0761: Partial method declarations of 'C<X>.H2<T, U>()' have inconsistent constraints for type parameter 'U' // partial void H2<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "H2").WithArguments("C<X>.H2<T, U>()", "U").WithLocation(29, 18), // (32,18): error CS0761: Partial method declarations of 'C<X>.K1<T, U>()' have inconsistent constraints for type parameter 'T' // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "K1").WithArguments("C<X>.K1<T, U>()", "T").WithLocation(32, 18), // (32,18): error CS0761: Partial method declarations of 'C<X>.K1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "K1").WithArguments("C<X>.K1<T, U>()", "U").WithLocation(32, 18), // (32,18): warning CS8826: Partial method declarations 'void C<X>.K1<U, T>()' and 'void C<X>.K1<T, U>()' have differences in parameter names, parameter types, or return types. // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "K1").WithArguments("void C<X>.K1<U, T>()", "void C<X>.K1<T, U>()").WithLocation(32, 18), // (33,18): warning CS8826: Partial method declarations 'void C<X>.K2<T1, T2>()' and 'void C<X>.K2<T, U>()' have differences in parameter names, parameter types, or return types. // partial void K2<T, U>() where T : class where U : T, IA<U> { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "K2").WithArguments("void C<X>.K2<T1, T2>()", "void C<X>.K2<T, U>()").WithLocation(33, 18), // (38,18): error CS0761: Partial method declarations of 'C<X>.A1<T>()' have inconsistent constraints for type parameter 'T' // partial void A1<T>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A1").WithArguments("C<X>.A1<T>()", "T").WithLocation(38, 18)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints02() { var source = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class C { partial void M1<T>() where T : A, NIBA; partial void M2<T>() where T : NA, IB<IA>; partial void M3<T, U>() where U : NIBAC; partial void M4<T, U>() where T : U, NIA; } partial class C { partial void M1<T>() where T : N.A, IB<IA> { } partial void M2<T>() where T : A, NIBA { } partial void M3<T, U>() where U : N.IB<A.IC> { } partial void M4<T, U>() where T : NIA { } } }"; CreateCompilation(source).VerifyDiagnostics( // (25,22): error CS0761: Partial method declarations of 'C.M4<T, U>()' have inconsistent constraints for type parameter 'T' // partial void M4<T, U>() where T : NIA { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "M4").WithArguments("N.C.M4<T, U>()", "T").WithLocation(25, 22)); } [Fact] public void CS07ERR_PartialMethodStaticDifference() { var text = @"partial class C { static partial void M1(); partial void M1() { } static partial void M2() { } partial void M2(); }"; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS07: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M1").WithLocation(4, 18), // (5,25): error CS07: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0764ERR_PartialMethodUnsafeDifference() { var text = @"partial class C { unsafe partial void M1(); partial void M1() { } unsafe partial void M2() { } partial void M2(); }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,18): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M1").WithLocation(4, 18), // (5,25): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0766ERR_PartialMethodMustReturnVoid() { var text = @" public partial class C { partial int Part(); partial int Part() { return 1; } public static int Main() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): error CS8794: Partial method 'C.Part()' must have accessibility modifiers because it has a non-void return type. // partial int Part(); Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "Part").WithArguments("C.Part()").WithLocation(5, 17), // (6,17): error CS8794: Partial method 'C.Part()' must have accessibility modifiers because it has a non-void return type. // partial int Part() Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "Part").WithArguments("C.Part()").WithLocation(6, 17)); } [Fact] public void CS0767ERR_ExplicitImplCollisionOnRefOut() { var text = @"interface IFace<T> { void Goo(ref T x); void Goo(out int x); } class A : IFace<int> { void IFace<int>.Goo(ref int x) { } void IFace<int>.Goo(out int x) { x = 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 }, //error for IFace<int, int>.Goo(ref int) new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 } //error for IFace<int, int>.Goo(out int) ); } [Fact] public void CS0825ERR_TypeVarNotFound01() { var text = @"namespace NS { class Test { static var myStaticField; extern private var M(); void MM(ref var v) { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,24): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // extern private var M(); Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (7,21): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // void MM(ref var v) { } Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (5,16): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // static var myStaticField; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (6,28): warning CS0626: Method, operator, or accessor 'NS.Test.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern private var M(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.M()"), // (5,20): warning CS0169: The field 'NS.Test.myStaticField' is never used // static var myStaticField; Diagnostic(ErrorCode.WRN_UnreferencedField, "myStaticField").WithArguments("NS.Test.myStaticField") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] [WorkItem(22512, "https://github.com/dotnet/roslyn/issues/22512")] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public int Num // CS0625 { get; set; } static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,20): error CS0625: 'Str.Num': instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute // public int Num // CS0625 Diagnostic(ErrorCode.ERR_MissingStructOffset, "Num").WithArguments("TestNamespace.Str.Num").WithLocation(9, 20) ); } [Fact] [WorkItem(1032724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032724")] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty_Bug1032724() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public static int Num { get; set; } static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0851ERR_OverloadRefOutCtor() { var text = @"namespace TestNamespace { class MyClass { public MyClass(ref int num) { } public MyClass(out int num) { num = 1; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,17): error CS0663: 'MyClass' cannot define an overloaded constructor that differs only on parameter modifiers 'out' and 'ref' // public MyClass(out int num) Diagnostic(ErrorCode.ERR_OverloadRefKind, "MyClass").WithArguments("TestNamespace.MyClass", "constructor", "out", "ref").WithLocation(8, 17)); } [Fact] public void CS1014ERR_GetOrSetExpected() { var source = @"partial class C { public object P { partial get; set; } object Q { get { return 0; } add { } } } "; CreateCompilation(source).VerifyDiagnostics( // (3,23): error CS1014: A get, set or init accessor expected // public object P { partial get; set; } Diagnostic(ErrorCode.ERR_GetOrSetExpected, "partial").WithLocation(3, 23), // (4,34): error CS1014: A get, set or init accessor expected // object Q { get { return 0; } add { } } Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 34)); } [Fact] public void CS1057ERR_ProtectedInStatic01() { var text = @"namespace NS { public static class B { protected static object field = null; internal protected static void M() {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 5, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 6, Column = 40 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CanNotDeclareProtectedPropertyInStaticClass() { const string text = @" static class B { protected static int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }); } [Fact] public void CanNotDeclareProtectedInternalPropertyInStaticClass() { const string text = @" static class B { internal static protected int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 37 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 42 }); } [Fact] public void CanNotDeclarePropertyWithProtectedInternalAccessorInStaticClass() { const string text = @" static class B { public static int X { get; protected internal set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic }); } /// <summary> /// variance /// </summary> [Fact] public void CS1067ERR_PartialWrongTypeParamsVariance01() { var text = @"namespace NS { //combinations partial interface I1<in T> { } partial interface I1<out T> { } partial interface I2<in T> { } partial interface I2<T> { } partial interface I3<T> { } partial interface I3<out T> { } //no duplicate errors partial interface I4<T, U> { } partial interface I4<out T, out U> { } //prefer over CS0264 partial interface I5<S> { } partial interface I5<out T> { } //no error after CS0264 partial interface I6<R, in T> { } partial interface I6<S, out T> { } //no error since arities don't match partial interface I7<T> { } partial interface I7<in T, U> { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,23): error CS1067: Partial declarations of 'NS.I1<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I1").WithArguments("NS.I1<T>"), // (7,23): error CS1067: Partial declarations of 'NS.I2<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I2").WithArguments("NS.I2<T>"), // (10,23): error CS1067: Partial declarations of 'NS.I3<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I3").WithArguments("NS.I3<T>"), // (14,23): error CS1067: Partial declarations of 'NS.I4<T, U>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I4").WithArguments("NS.I4<T, U>"), // (18,23): error CS1067: Partial declarations of 'NS.I5<S>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I5").WithArguments("NS.I5<S>"), // (22,23): error CS0264: Partial declarations of 'NS.I6<R, T>' must have the same type parameter names in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParams, "I6").WithArguments("NS.I6<R, T>")); } [Fact] public void CS1100ERR_BadThisParam() { var text = @"static class Test { static void ExtMethod(int i, this Goo1 c) // CS1100 { } } class Goo1 { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (3,34): error CS1100: Method 'ExtMethod' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("ExtMethod").WithLocation(3, 34)); } [Fact] public void CS1103ERR_BadTypeforThis01() { // Note that the dev11 compiler does not report error CS0721, that C cannot be used as a parameter type. // This appears to be a shortcoming of the dev11 compiler; there is no good reason to not report the error. var compilation = CreateCompilation( @"static class C { static void M1(this Unknown u) { } static void M2(this C c) { } static void M3(this dynamic d) { } static void M4(this dynamic[] d) { } }"); compilation.VerifyDiagnostics( // (3,25): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown"), // (4,17): error CS0721: 'C': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M2").WithArguments("C"), // (5,25): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic")); } [Fact] public void CS1103ERR_BadTypeforThis02() { CreateCompilation( @"public static class Extensions { public unsafe static char* Test(this char* charP) { return charP; } // CS1103 } ", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadTypeforThis, "char*").WithArguments("char*").WithLocation(3, 42)); } [Fact] public void CS1105ERR_BadExtensionMeth() { var text = @"public class Extensions { public void Test<T>(this System.String s) { } //CS1105 } "; var reference = SystemCoreRef; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { reference }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadExtensionAgg, Line = 1, Column = 14 }); } [Fact] public void CS1106ERR_BadExtensionAgg01() { var compilation = CreateCompilation( @"class A { static void M(this object o) { } } class B { static void M<T>(this object o) { } } static class C<T> { static void M(this object o) { } } static class D<T> { static void M<U>(this object o) { } } struct S { static void M(this object o) { } } struct T { static void M<U>(this object o) { } } struct U<T> { static void M(this object o) { } }"); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExtensionAgg, "A").WithLocation(1, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(5, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(9, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "D").WithLocation(13, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "S").WithLocation(17, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "T").WithLocation(21, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "U").WithLocation(25, 8)); } [WorkItem(528256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528256")] [Fact()] public void CS1106ERR_BadExtensionAgg02() { CreateCompilation( @"interface I { static void M(this object o); }", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (3,17): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static void M(this object o); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M").WithArguments("static", "7.0", "8.0").WithLocation(3, 17), // (1,11): error CS1106: Extension method must be defined in a non-generic static class // interface I Diagnostic(ErrorCode.ERR_BadExtensionAgg, "I").WithLocation(1, 11), // (3,17): error CS0501: 'I.M(object)' must declare a body because it is not marked abstract, extern, or partial // static void M(this object o); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("I.M(object)").WithLocation(3, 17) ); } [Fact] public void CS1109ERR_ExtensionMethodsDecl() { var compilation = CreateCompilation( @"class A { static class C { static void M(this object o) { } } } static class B { static class C { static void M(this object o) { } } } struct S { static class C { static void M(this object o) { } } }"); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(5, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(12, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(19, 21)); } [Fact] public void CS1110ERR_ExtensionAttrNotFound() { //Extension method cannot be declared without a reference to System.Core.dll var source = @"static class A { public static void M1(this object o) { } public static void M2(this string s, this object o) { } public static void M3(this dynamic d) { } } class B { public static void M4(this object o) { } }"; var compilation = CreateEmptyCompilation(source, new[] { TestMetadata.Net40.mscorlib }); compilation.VerifyDiagnostics( // (3,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(3, 27), // (4,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(4, 27), // (4,42): error CS1100: Method 'M2' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M2").WithLocation(4, 42), // (5,32): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic").WithLocation(5, 32), // (5,32): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(5, 32), // (7,7): error CS1106: Extension methods must be defined in a non-generic static class Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(7, 7)); } [Fact] public void CS1112ERR_ExplicitExtension() { var source = @"using System.Runtime.CompilerServices; [System.Runtime.CompilerServices.ExtensionAttribute] static class A { static void M(object o) { } } static class B { [Extension] static void M() { } [ExtensionAttribute] static void M(this object o) { } [Extension] static object P { [Extension] get { return null; } } [Extension(0)] static object F; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [System.Runtime.CompilerServices.ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "System.Runtime.CompilerServices.ExtensionAttribute"), // (9,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (11,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "ExtensionAttribute"), // (13,6): error CS0592: Attribute 'Extension' is not valid on this declaration type. It is only valid on 'assembly, class, method' declarations. // [Extension] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Extension").WithArguments("Extension", "assembly, class, method"), // (16,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (19,6): error CS1729: 'System.Runtime.CompilerServices.ExtensionAttribute' does not contain a constructor that takes 1 arguments // [Extension(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Extension(0)").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "1"), // (20,19): warning CS0169: The field 'B.F' is never used // static object F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F")); } [Fact] public void CS1509ERR_ImportNonAssembly() { //CSC /TARGET:library /reference:class1.netmodule text.CS var text = @"class Test { public static int Main() { return 1; } }"; var ref1 = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "NetModule.mod"); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // error CS1509: The referenced file 'NetModule.mod' is not an assembly Diagnostic(ErrorCode.ERR_ImportNonAssembly).WithArguments(@"NetModule.mod")); } [Fact] public void CS1527ERR_NoNamespacePrivate1() { var text = @"private class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 15 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate2() { var text = @"protected class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 17 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate3() { var text = @"protected internal class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 26 } //pos = the class name ); } [Fact] public void CS1537ERR_DuplicateAlias1() { var text = @"using A = System; using A = System; namespace NS { using O = System.Object; using O = System.Object; }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,7): error CS1537: The using alias 'A' appeared previously in this namespace // using A = System; Diagnostic(ErrorCode.ERR_DuplicateAlias, "A").WithArguments("A"), // (7,11): error CS1537: The using alias 'O' appeared previously in this namespace // using O = System.Object; Diagnostic(ErrorCode.ERR_DuplicateAlias, "O").WithArguments("O"), // (1,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (2,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (6,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;"), // (7,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [WorkItem(537684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537684")] [Fact] public void CS1537ERR_DuplicateAlias2() { var text = @"namespace namespace1 { class A { } } namespace namespace2 { class B { } } namespace NS { using ns = namespace1; using ns = namespace2; using System; class C : ns.A { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,11): error CS1537: The using alias 'ns' appeared previously in this namespace // using ns = namespace2; Diagnostic(ErrorCode.ERR_DuplicateAlias, "ns").WithArguments("ns"), // (14,5): info CS8019: Unnecessary using directive. // using ns = namespace2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ns = namespace2;"), // (15,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("C").Single() as NamedTypeSymbol; var b = type1.BaseType(); } [Fact] public void CS1537ERR_DuplicateAlias3() { var text = @"using X = System; using X = ABC.X<int>;"; CreateCompilation(text).VerifyDiagnostics( // (2,7): error CS1537: The using alias 'X' appeared previously in this namespace // using X = ABC.X<int>; Diagnostic(ErrorCode.ERR_DuplicateAlias, "X").WithArguments("X"), // (1,1): info CS8019: Unnecessary using directive. // using X = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = System;"), // (2,1): info CS8019: Unnecessary using directive. // using X = ABC.X<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = ABC.X<int>;")); } [WorkItem(539125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539125")] [Fact] public void CS1542ERR_AddModuleAssembly() { //CSC /addmodule:cs1542.dll /TARGET:library text1.cs var text = @"public class Goo : IGoo { public void M0() { } }"; var ref1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.NoMsCorLibRef).GetReference(display: "NoMsCorLibRef.mod"); CreateCompilation(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1542: 'NoMsCorLibRef.mod' cannot be added to this assembly because it already is an assembly Diagnostic(ErrorCode.ERR_AddModuleAssembly).WithArguments(@"NoMsCorLibRef.mod"), // (1,20): error CS0246: The type or namespace name 'IGoo' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IGoo").WithArguments("IGoo")); } [Fact, WorkItem(544910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544910")] public void CS1599ERR_MethodReturnCantBeRefAny() { var text = @" using System; interface I { ArgIterator M(); // 1599 } class C { public delegate TypedReference Test1(); // 1599 public RuntimeArgumentHandle Test2() // 1599 { return default(RuntimeArgumentHandle); } // The native compiler does not catch this one; Roslyn does. public static ArgIterator operator +(C c1, C c2) // 1599 { return default(ArgIterator); } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (5,5): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.ArgIterator' // ArgIterator M(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (11,12): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.RuntimeArgumentHandle' // public RuntimeArgumentHandle Test2() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle"), // (17,19): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.ArgIterator' // public static ArgIterator operator +(C c1, C c2) // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (9,21): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.TypedReference' // public delegate TypedReference Test1(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference") ); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionReturnCantBeRefAny() { var text = @" class C { public void Goo() { System.TypedReference local1() // 1599 { return default; } local1(); System.RuntimeArgumentHandle local2() // 1599 { return default; } local2(); System.ArgIterator local3() // 1599 { return default; } local3(); } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (6,9): error CS1599: The return type of a method, delegate, or function pointer cannot be 'TypedReference' // System.TypedReference local1() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(6, 9), // (12,9): error CS1599: The return type of a method, delegate, or function pointer cannot be 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle local2() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(12, 9), // (18,9): error CS1599: The return type of a method, delegate, or function pointer cannot be 'ArgIterator' // System.ArgIterator local3() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(18, 9)); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionReturnCanBeSpan() { var text = @" using System; class C { static void M() { byte[] bytes = new byte[1]; Span<byte> local1() { return new Span<byte>(bytes); } Span<byte> res = local1(); } } "; CreateCompilationWithMscorlibAndSpanSrc(text).VerifyDiagnostics(); } [Fact, WorkItem(544910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544910")] public void CS1601ERR_MethodArgCantBeRefAny() { // We've changed the text of the error message from // CS1601: Method or delegate parameter cannot be of type 'ref System.TypedReference' // to // CS1601: Cannot make reference to variable of type 'System.TypedReference' // because we use this error message at both the call site and the declaration. // The new wording makes sense in both uses; the former only makes sense at // the declaration site. var text = @" using System; class MyClass { delegate void D(ref TypedReference t1); // CS1601 public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 { var x = __makeref(r3); // CS1601 } public void Test2(out ArgIterator t4) // CS1601 { t4 = default(ArgIterator); } MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (6,23): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t2").WithArguments("System.TypedReference"), // (11,23): error CS1601: Cannot make reference to variable of type 'System.ArgIterator' // public void Test2(out ArgIterator t4) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator t4").WithArguments("System.ArgIterator"), // (16,13): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref RuntimeArgumentHandle r5").WithArguments("System.RuntimeArgumentHandle"), // (5,21): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // delegate void D(ref TypedReference t1); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t1").WithArguments("System.TypedReference"), // (8,17): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // var x = __makeref(r3); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "__makeref(r3)").WithArguments("System.RuntimeArgumentHandle") ); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionParamCantBeRefAny() { var text = @" class C { public void Goo() { { System.TypedReference _arg = default; void local1(ref System.TypedReference tr) { } // 1601 local1(ref _arg); void local2(in System.TypedReference tr) { } // 1601 local2(in _arg); void local3(out System.TypedReference tr) // 1601 { tr = default; } local3(out _arg); } { System.ArgIterator _arg = default; void local1(ref System.ArgIterator ai) { } // 1601 local1(ref _arg); void local2(in System.ArgIterator ai) { } // 1601 local2(in _arg); void local3(out System.ArgIterator ai) // 1601 { ai = default; } local3(out _arg); } { System.RuntimeArgumentHandle _arg = default; void local1(ref System.RuntimeArgumentHandle ah) { } // 1601 local1(ref _arg); void local2(in System.RuntimeArgumentHandle ah) { } // 1601 local2(in _arg); void local3(out System.RuntimeArgumentHandle ah) // 1601 { ah = default; } local3(out _arg); } } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (8,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local1(ref System.TypedReference tr) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(8, 25), // (11,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local2(in System.TypedReference tr) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(11, 25), // (14,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local3(out System.TypedReference tr) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(14, 25), // (23,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local1(ref System.ArgIterator ai) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(23, 25), // (26,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local2(in System.ArgIterator ai) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(26, 25), // (29,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local3(out System.ArgIterator ai) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(29, 25), // (38,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local1(ref System.RuntimeArgumentHandle ah) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(38, 25), // (41,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local2(in System.RuntimeArgumentHandle ah) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(41, 25), // (44,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local3(out System.RuntimeArgumentHandle ah) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(44, 25)); } [WorkItem(542003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542003")] [Fact] public void CS1608ERR_CantUseRequiredAttribute() { var text = @"using System.Runtime.CompilerServices; [RequiredAttribute(typeof(object))] class ClassMain { }"; CreateCompilation(text).VerifyDiagnostics( // (3,2): error CS1608: The Required attribute is not permitted on C# types // [RequiredAttribute(typeof(object))] Diagnostic(ErrorCode.ERR_CantUseRequiredAttribute, "RequiredAttribute").WithLocation(3, 2)); } [Fact] public void CS1614ERR_AmbiguousAttribute() { var text = @"using System; class A : Attribute { } class AAttribute : Attribute { } [A][@A][AAttribute] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbiguousAttribute, Line = 4, Column = 2 }); } [Fact] public void CS0214ERR_RequiredInUnsafeContext() { var text = @"struct C { public fixed int ab[10]; // CS0214 } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); // (3,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed string ab[10]; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "ab[10]"); } [Fact] public void CS1642ERR_FixedNotInStruct() { var text = @"unsafe class C { fixed int a[10]; // CS1642 }"; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,15): error CS1642: Fixed size buffer fields may only be members of structs // fixed int a[10]; // CS1642 Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a")); } [Fact] public void CS1663ERR_IllegalFixedType() { var text = @"unsafe struct C { fixed string ab[10]; // CS1663 }"; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,11): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // fixed string ab[10]; // CS1663 Diagnostic(ErrorCode.ERR_IllegalFixedType, "string")); } [WorkItem(545353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545353")] [Fact] public void CS1664ERR_FixedOverflow() { // set Allow unsafe code = true var text = @"public unsafe struct C { unsafe private fixed long test_1[1073741825]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,38): error CS1664: Fixed size buffer of length '1073741825' and type 'long' is too big // unsafe private fixed long test_1[1073741825]; Diagnostic(ErrorCode.ERR_FixedOverflow, "1073741825").WithArguments("1073741825", "long")); } [WorkItem(545353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545353")] [Fact] public void CS1665ERR_InvalidFixedArraySize() { var text = @"unsafe struct S { public unsafe fixed int A[0]; // CS1665 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS1665: Fixed size buffers must have a length greater than zero // public unsafe fixed int A[0]; // CS1665 Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "0")); } [WorkItem(546922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546922")] [Fact] public void CS1665ERR_InvalidFixedArraySizeNegative() { var text = @"unsafe struct S { public unsafe fixed int A[-1]; // CS1665 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "-1")); } [Fact()] public void CS0443ERR_InvalidFixedArraySizeNotSpecified() { var text = @"unsafe struct S { public unsafe fixed int A[]; // CS0443 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS0443: Syntax error; value expected // public unsafe fixed int A[]; // CS0443 Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void CS1003ERR_InvalidFixedArrayMultipleDimensions() { var text = @"unsafe struct S { public unsafe fixed int A[2,2]; // CS1003,CS1001 public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,33): error CS1002: ; expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_SemicolonExpected, "["), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,36): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";"), // (3,30): error CS7092: A fixed buffer may only have one dimension. // public unsafe fixed int A[2,2]; // CS1003,CS1001 Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[2,2]")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested() { var text = @"unsafe struct S { unsafe class Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; //Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferInner[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferInner")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested_2() { var text = @"unsafe class S { unsafe struct Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; // Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferOuter[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferOuter")); } [Fact] public void CS0133ERR_InvalidFixedBufferCountFromField() { var text = @"unsafe struct s { public static int var1 = 10; public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,34): error CS0133: The expression being assigned to 's._Type3' must be constant // public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "var1").WithArguments("s._Type3")); } [Fact] public void CS1663ERR_InvalidFixedBufferUsingGenericType() { var text = @"unsafe struct Err_FixedBufferDeclarationUsingGeneric<t> { public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "t")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypes() { var text = @"unsafe struct s { public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) public fixed int _Type2[true]; // error CS00029 public fixed int _Type3[""true""]; // error CS00029 public fixed int _Type4[System.Convert.ToInt32(@""1"")]; // error CS0133 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,33): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.2").WithArguments("double", "int"), // (4,33): error CS0029: Cannot implicitly convert type 'bool' to 'int' // public fixed int _Type2[true]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, "true").WithArguments("bool", "int"), // (5,33): error CS0029: Cannot implicitly convert type 'string' to 'int' // public fixed int _Type3["true"]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""true""").WithArguments("string", "int"), // (6,33): error CS0133: The expression being assigned to 's._Type4' must be constant // public fixed int _Type4[System.Convert.ToInt32(@"1")]; // error CS0133 Diagnostic(ErrorCode.ERR_NotConstantExpression, @"System.Convert.ToInt32(@""1"")").WithArguments("s._Type4")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypesUserDefinedTypes() { var text = @"unsafe struct s { public fixed goo _bufferGoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } struct goo { public int ABC; } class bar { public bool ABC = true; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed goo _bufferGoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "goo"), // (4,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "bar"), // (9,20): warning CS0649: Field 'goo.ABC' is never assigned to, and will always have its default value 0 // public int ABC; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ABC").WithArguments("goo.ABC", "0")); } [Fact] public void C1666ERR_InvalidFixedBufferInUnfixedContext() { var text = @" unsafe struct s { private fixed ushort _e_res[4]; void Error_UsingFixedBuffersWithThis() { ushort c = this._e_res; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,24): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. // ushort c = this._e_res; Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "this._e_res")); } [Fact] public void CS0029ERR_InvalidFixedBufferUsageInLocal() { //Some additional errors generated but the key ones from native are here. var text = @"unsafe struct s { //Use as local rather than field with unsafe on method // Incorrect usage of fixed buffers in method bodies try to use as a local static unsafe void Error_UseAsLocal() { //Invalid In Use as Local fixed bool _buffer[2]; // error CS1001: Identifier expected } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,15): error CS1003: Syntax error, '(' expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_SyntaxError, "bool").WithArguments("(", "bool"), // (8,27): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CStyleArray, "[2]"), // (8,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "2"), // (8,30): error CS1026: ) expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CloseParenExpected, ";"), // (8,30): warning CS0642: Possible mistaken empty statement // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_BadFixedInitType, "_buffer[2]"), // (8,20): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_FixedMustInit, "_buffer[2]")); } [Fact()] public void CS1667ERR_AttributeNotOnAccessor() { var text = @"using System; public class C { private int i; public int ObsoleteProperty { [Obsolete] // CS1667 get { return i; } [System.Diagnostics.Conditional(""Bernard"")] set { i = value; } } public static void Main() { } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (10,10): error CS1667: Attribute 'System.Diagnostics.Conditional' is not valid on property or event accessors. It is only valid on 'class, method' declarations. // [System.Diagnostics.Conditional("Bernard")] Diagnostic(ErrorCode.ERR_AttributeNotOnAccessor, "System.Diagnostics.Conditional").WithArguments("System.Diagnostics.Conditional", "class, method") ); } [Fact] public void CS1689ERR_ConditionalOnNonAttributeClass() { var text = @"[System.Diagnostics.Conditional(""A"")] // CS1689 class MyClass {} "; CreateCompilation(text).VerifyDiagnostics( // (1,2): error CS1689: Attribute 'System.Diagnostics.Conditional' is only valid on methods or attribute classes // [System.Diagnostics.Conditional("A")] // CS1689 Diagnostic(ErrorCode.ERR_ConditionalOnNonAttributeClass, @"System.Diagnostics.Conditional(""A"")").WithArguments("System.Diagnostics.Conditional").WithLocation(1, 2)); } // CS17ERR_DuplicateImport: See ReferenceManagerTests.CS17ERR_DuplicateImport // CS1704ERR_DuplicateImportSimple: See ReferenceManagerTests.CS1704ERR_DuplicateImportSimple [Fact(Skip = "530901"), WorkItem(530901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530901")] public void CS1705ERR_AssemblyMatchBadVersion() { // compile with: /target:library /out:c:\\cs1705.dll /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""1.0"")] public class A { public void M1() {} public class N1 {} public void M2() {} public class N2 {} } public class C1 {} public class C2 {} "; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); // compile with: /target:library /out:cs1705.dll /keyfile:mykey.snk var text2 = @"using System.Reflection; [assembly:AssemblyVersion(""2.0"")] public class A { public void M2() {} public class N2 {} public void M1() {} public class N1 {} } public class C2 {} public class C1 {} "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); // compile with: /target:library /r:A2=c:\\CS1705.dll /r:A1=CS1705.dll var text3 = @"extern alias A1; extern alias A2; using a1 = A1::A; using a2 = A2::A; using n1 = A1::A.N1; using n2 = A2::A.N2; public class Ref { public static a1 A1() { return new a1(); } public static a2 A2() { return new a2(); } public static A1::C1 M1() { return new A1::C1(); } public static A2::C2 M2() { return new A2::C2(); } public static n1 N1() { return new a1.N1(); } public static n2 N2() { return new a2.N2(); } } "; var tree3 = SyntaxFactory.ParseCompilationUnit(text3); // compile with: /reference:c:\\CS1705.dll /reference:CS1705_c.dll var text = @"class Tester { static void Main() { Ref.A1().M1(); Ref.A2().M2(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AssemblyMatchBadVersion, Line = 2, Column = 12 }); } [Fact] public void CS1715ERR_CantChangeTypeOnOverride() { var text = @"abstract public class Base { abstract public int myProperty { get; set; } } public class Derived : Base { int myField; public override double myProperty // CS1715 { get { return myField; } set { myField= 1; } } public static void Main() { } } "; // The set accessor has the wrong parameter type so is not implemented. // The override get accessor has the right signature (no parameters) so is implemented, though with the wrong return type. CreateCompilation(text).VerifyDiagnostics( // (10,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.myProperty.set' // public class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.myProperty.set").WithLocation(10, 14), // (13,28): error CS1715: 'Derived.myProperty': type must be 'int' to match overridden member 'Base.myProperty' // public override double myProperty // CS1715 Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "myProperty").WithArguments("Derived.myProperty", "Base.myProperty", "int").WithLocation(13, 28) ); } [Fact] public void CS1716ERR_DoNotUseFixedBufferAttr() { var text = @" using System.Runtime.CompilerServices; public struct UnsafeStruct { [FixedBuffer(typeof(int), 4)] // CS1716 unsafe public int aField; } public class TestUnsafe { static void Main() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,6): error CS1716: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead. // [FixedBuffer(typeof(int), 4)] // CS1716 Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttr, "FixedBuffer").WithLocation(6, 6)); } [Fact] public void CS1721ERR_NoMultipleInheritance01() { var text = @"namespace NS { public class A { } public class B { } public class C : B { } public class MyClass : A, A { } // CS1721 public class MyClass2 : A, B { } // CS1721 public class MyClass3 : C, A { } // CS1721 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 7, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 8, Column = 32 }); } [Fact] public void CS1722ERR_BaseClassMustBeFirst01() { var text = @"namespace NS { public class A { } interface I { } interface IGoo<T> : I { } public class MyClass : I, A { } // CS1722 public class MyClass2 : A, I { } // OK class Test { class C : IGoo<int>, A , I { } // CS1722 } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 7, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 30 }); } [Fact(), WorkItem(530393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530393")] public void CS1724ERR_InvalidDefaultCharSetValue() { var text = @" using System.Runtime.InteropServices; [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 class C { [DllImport(""F.Dll"")] extern static void FW1Named(); static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,34): error CS0591: Invalid value for argument to 'DefaultCharSetAttribute' attribute // [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(CharSet)42").WithArguments("DefaultCharSetAttribute") ); } [Fact, WorkItem(1116455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116455")] public void CS1725ERR_FriendAssemblyBadArgs() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Test, Version=*"")] // ok [assembly: InternalsVisibleTo(""Test, PublicKeyToken=*"")] // ok [assembly: InternalsVisibleTo(""Test, Culture=*"")] // ok [assembly: InternalsVisibleTo(""Test, Retargetable=*"")] // ok [assembly: InternalsVisibleTo(""Test, ContentType=*"")] // ok [assembly: InternalsVisibleTo(""Test, Version=."")] // ok [assembly: InternalsVisibleTo(""Test, Version=.."")] // ok [assembly: InternalsVisibleTo(""Test, Version=..."")] // ok [assembly: InternalsVisibleTo(""Test, Version=1"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")] // error [assembly: InternalsVisibleTo(""Test, CuLTure=EN"")] // error [assembly: InternalsVisibleTo(""Test, PublicKeyToken=null"")] // ok "; // Tested against Dev12 CreateCompilation(text).VerifyDiagnostics( // (12,12): error CS1725: Friend assembly reference 'Test, Version=1' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1"")").WithArguments("Test, Version=1").WithLocation(12, 12), // (13,12): error CS1725: Friend assembly reference 'Test, Version=1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.*"")").WithArguments("Test, Version=1.*").WithLocation(13, 12), // (14,12): error CS1725: Friend assembly reference 'Test, Version=1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.*"")").WithArguments("Test, Version=1.1.*").WithLocation(14, 12), // (15,12): error CS1725: Friend assembly reference 'Test, Version=1.1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.1.*"")").WithArguments("Test, Version=1.1.1.*").WithLocation(15, 12), // (16,12): error CS1725: Friend assembly reference 'Test, ProcessorArchitecture=MSIL' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")").WithArguments("Test, ProcessorArchitecture=MSIL").WithLocation(16, 12), // (17,12): error CS1725: Friend assembly reference 'Test, CuLTure=EN' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, CuLTure=EN"")").WithArguments("Test, CuLTure=EN").WithLocation(17, 12)); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant01() { var text = @"class A { static int Age; public void Goo(int Para1 = Age) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,33): error CS1736: Default parameter value for 'Para1' must be a compile-time constant // public void Goo(int Para1 = Age) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Age").WithArguments("Para1"), // (3,16): warning CS0169: The field 'A.Age' is never used // static int Age; Diagnostic(ErrorCode.WRN_UnreferencedField, "Age").WithArguments("A.Age") ); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant02() { var source = @"class C { object this[object x, object y = new C()] { get { return null; } set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (3,38): error CS1736: Default parameter value for 'y' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new C()").WithArguments("y").WithLocation(3, 38)); } [Fact, WorkItem(542401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542401")] public void CS1736ERR_DefaultValueMustBeConstant_1() { var text = @" class NamedExample { static int y = 1; static void Main(string[] args) { } int CalculateBMI(int weight, int height = y) { return (weight * 7) / (height * height); } } "; CreateCompilation(text).VerifyDiagnostics( // (9,47): error CS1736: Default parameter value for 'height' must be a compile-time constant // int CalculateBMI(int weight, int height = y) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "y").WithArguments("height"), // (4,16): warning CS0414: The field 'NamedExample.y' is assigned but its value is never used // static int y = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "y").WithArguments("NamedExample.y") ); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @"class A { public void Goo(int Para1 = 1, int Para2) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1737, Line = 3, Column = 45 }); } [Fact] public void CS1741ERR_RefOutDefaultValue() { var text = @"class A { public void Goo(ref int Para1 = 1) { } public void Goo1(out int Para2 = 1) { Para2 = 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1741, Line = 3, Column = 21 }, new ErrorDescription { Code = 1741, Line = 5, Column = 22 }); } [Fact] public void CS17ERR_DefaultValueForExtensionParameter() { var text = @"static class C { static void M1(object o = null) { } static void M2(this object o = null) { } static void M3(object o, this int i = 0) { } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (4,20): error CS17: Cannot specify a default value for the 'this' parameter Diagnostic(ErrorCode.ERR_DefaultValueForExtensionParameter, "this").WithLocation(4, 20), // (5,30): error CS1100: Method 'M3' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M3").WithLocation(5, 30)); } [Fact] public void CS1745ERR_DefaultValueUsedWithAttributes() { var text = @" using System.Runtime.InteropServices; class A { public void goo([OptionalAttribute]int p = 1) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,22): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void goo([OptionalAttribute]int p = 1) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "OptionalAttribute") ); } [Fact] public void CS1747ERR_NoPIAAssemblyMissingAttribute() { //csc program.cs /l:"C:\MissingPIAAttributes.dll var text = @"public class Test { static int Main(string[] args) { return 1; } }"; var ref1 = TestReferences.SymbolsTests.NoPia.Microsoft.VisualStudio.MissingPIAAttributes.WithEmbedInteropTypes(true); CreateCompilation(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1747: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.GuidAttribute").WithLocation(1, 1), // error CS1759: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttributes).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute").WithLocation(1, 1)); } [WorkItem(620366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620366")] [Fact] public void CS1748ERR_NoCanonicalView() { var textdll = @" using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTest"")] [assembly: Guid(""A55E0B17-2558-447D-B786-84682CBEF136"")] [assembly: BestFitMapping(false)] [ComImport, Guid(""E245C65D-2448-447A-B786-64682CBEF133"")] [TypeIdentifier(""E245C65D-2448-447A-B786-64682CBEF133"", ""IMyInterface"")] public interface IMyInterface { void Method(int n); } public delegate void DelegateWithInterface(IMyInterface value); public delegate void DelegateWithInterfaceArray(IMyInterface[] ary); public delegate IMyInterface DelegateRetInterface(); public delegate DelegateRetInterface DelegateRetDelegate(DelegateRetInterface d); "; var text = @" class Test { static void Main() { } public static void MyDelegate02(IMyInterface[] ary) { } } "; var comp1 = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp1); CreateCompilation(text, references: new MetadataReference[] { ref1 }).VerifyDiagnostics( // (77): error CS0246: The type or namespace name 'IMyInterface' could not be found (are you missing a using directive or an assembly reference?) // public static void MyDelegate02(IMyInterface[] ary) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IMyInterface").WithArguments("IMyInterface") ); } [Fact] public void CS1750ERR_NoConversionForDefaultParam() { var text = @"public class Generator { public void Show<T>(string msg = ""Number"", T value = null) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1750, Line = 3, Column = 50 }); } [Fact] public void CS1751ERR_DefaultValueForParamsParameter() { // The native compiler only produces one error here -- that // the default value on "params" is illegal. However it // seems reasonable to produce one error for each bad param. var text = @"class MyClass { public void M7(int i = null, params string[] values = ""test"") { } static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // 'i': A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'int' new ErrorDescription { Code = 1750, Line = 3, Column = 24 }, // 'params': error CS1751: Cannot specify a default value for a parameter array new ErrorDescription { Code = 1751, Line = 3, Column = 34 }); } [ConditionalFact(typeof(DesktopOnly))] public void CS1754ERR_NoPIANestedType() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyClass { public struct NestedClass { public string Name; } } } "; var text = @"public class Test { public static void Main() { var S = new NS.MyClass.NestedClass(); System.Console.Write(S); } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoPIANestedType, "NestedClass").WithArguments("NS.MyClass.NestedClass")); } [Fact()] public void CS1755ERR_InvalidTypeIdentifierConstructor() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { [TypeIdentifier(""Goo2"", ""Bar2"")] public delegate void MyDel(); } "; var text = @" public class Test { event NS.MyDel e; public static void Main() { } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // (4,14): error CS0234: The type or namespace name 'MyDel' does not exist in the namespace 'NS' (are you missing an assembly reference?) // event NS.MyDel e; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MyDel").WithArguments("MyDel", "NS"), // (4,20): warning CS0067: The event 'Test.e' is never used // event NS.MyDel e; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("Test.e")); //var comp1 = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(new List<string>() { text }, new List<MetadataReference>() { ref1 }, // new ErrorDescription { Code = 1755, Line = 4, Column = 14 }); } [ConditionalFact(typeof(DesktopOnly))] public void CS1757ERR_InteropStructContainsMethods() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyStruct { private int _age; public string Name; } } "; var text = @"public class Test { public static void Main() { NS.MyStruct S = new NS.MyStruct(); System.Console.Write(S); } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); var comp1 = CreateCompilation(text, new[] { ref1 }); comp1.VerifyEmitDiagnostics( // (5,24): error CS1757: Embedded interop struct 'NS.MyStruct' can contain only public instance fields. // NS.MyStruct S = new NS.MyStruct(); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "new NS.MyStruct()").WithArguments("NS.MyStruct")); } [Fact] public void CS1754ERR_NoPIANestedType_2() { //vbc /t:library PIA.vb //csc /l:PIA.dll Program.cs var textdll = @"Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib(""GeneralPIA.dll"")> <Assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedClass Class InnerClass End Class End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedStructure Structure InnerStructure End Structure End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedEnum Enum InnerEnum Value1 End Enum End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedDelegate Delegate Sub InnerDelegate() End Interface Public Structure NestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Structure Public Structure NestedClass Class InnerClass End Class End Structure Public Structure NestedStructure Structure InnerStructure End Structure End Structure Public Structure NestedEnum Enum InnerEnum Value1 End Enum End Structure Public Structure NestedDelegate Delegate Sub InnerDelegate() End Structure"; var text = @"public class Program { public static void Main() { INestedInterface.InnerInterface s1 = null; INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); INestedDelegate.InnerDelegate s5 = null; } }"; var vbcomp = VisualBasic.VisualBasicCompilation.Create( "Test", new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(textdll) }, new[] { MscorlibRef_v4_0_30316_17626 }, new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var ref1 = vbcomp.EmitToImageReference(embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // (5,26): error CS1754: Type 'INestedInterface.InnerInterface' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerInterface").WithArguments("INestedInterface.InnerInterface"), // (6,26): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (6,71): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (7,21): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (7,56): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (8,25): error CS1754: Type 'INestedDelegate.InnerDelegate' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerDelegate").WithArguments("INestedDelegate.InnerDelegate"), // (5,41): warning CS0219: The variable 's1' is assigned but its value is never used // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1"), // (6,41): warning CS0219: The variable 's3' is assigned but its value is never used // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s3").WithArguments("s3"), // (71): warning CS0219: The variable 's4' is assigned but its value is never used // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s4").WithArguments("s4"), // (8,39): warning CS0219: The variable 's5' is assigned but its value is never used // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s5").WithArguments("s5")); } [Fact] public void CS17ERR_NotNullRefDefaultParameter() { var text = @" public static class ErrorCode { // We do not allow constant conversions from string to object in a default parameter initializer static void M1(object x = ""hello"") {} // We do not allow boxing conversions to object in a default parameter initializer static void M2(System.ValueType y = 123) {} }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // (5,25): error CS17: 'x' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 5, Column = 25 }, // (75): error CS17: 'y' is of type 'System.ValueType'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 7, Column = 35 }); } [WorkItem(619266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619266")] [Fact(Skip = "619266")] public void CS1768ERR_GenericsUsedInNoPIAType() { // add dll and make it embed var textdll = @"using System; using System.Collections.Generic; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace ClassLibrary3 { [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed5"")] public interface IGoo { IBar<string> goo(); } [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed6"")] public interface IBar<T> { List<IGoo> GetList(); } } "; var text = @" using System.Collections.Generic; using ClassLibrary3; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { IGoo x = (IGoo)new object(); } } class goo : IBar<string>, IGoo { public List<string> GetList() { throw new NotImplementedException(); } List<IGoo> IBar<string>.GetList() { throw new NotImplementedException(); } } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_GenericsUsedInNoPIAType)); } [Fact, WorkItem(6186, "https://github.com/dotnet/roslyn/issues/6186")] public void CS1770ERR_NoConversionForNubDefaultParam() { var text = @"using System; class MyClass { public enum E { None } // No error: public void Goo1(int? x = default(int)) { } public void Goo2(E? x = default(E)) { } public void Goo3(DateTime? x = default(DateTime?)) { } public void Goo4(DateTime? x = new DateTime?()) { } // Error: public void Goo11(DateTime? x = default(DateTime)) { } public void Goo12(DateTime? x = new DateTime()) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,33): error CS1770: A value of type 'DateTime' cannot be used as default parameter for nullable parameter 'x' because 'DateTime' is not a simple type // public void Goo11(DateTime? x = default(DateTime)) { } Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("System.DateTime", "x").WithLocation(13, 33), // (14,33): error CS1770: A value of type 'DateTime' cannot be used as default parameter for nullable parameter 'x' because 'DateTime' is not a simple type // public void Goo12(DateTime? x = new DateTime()) { } Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("System.DateTime", "x").WithLocation(14, 33) ); } [Fact] public void CS1908ERR_DefaultValueTypeMustMatch() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Bad([Optional] [DefaultParameterValue(""true"")] bool b); // CS1908 } "; CreateCompilation(text).VerifyDiagnostics( // (4,26): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } // Dev10 reports CS1909: The DefaultValue attribute is not applicable on parameters of type '{0}'. // for parameters of type System.Type or array even though there is no reason why null couldn't be specified in DPV. // We report CS1910 if DPV has an argument of type System.Type or array like Dev10 does except for we do so instead // of CS1909 when non-null is passed. [Fact] public void CS1909ERR_DefaultValueBadValueType_Array_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]int[] arr1); } "; // Dev10 reports CS1909, we don't CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Array() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(new int[] { 1, 2 })]object a); void Test2([DefaultParameterValue(new int[] { 1, 2 })]int[] a); void Test3([DefaultParameterValue(new int[0])]int[] a); } "; // CS1910 CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (5,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (6,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]")); } [Fact] public void CS1909ERR_DefaultValueBadValueType_Type_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]System.Type t); } "; // Dev10 reports CS1909, we don't CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValue_Generics() { var text = @"using System.Runtime.InteropServices; public class C { } public interface ISomeInterface { void Test1<T>([DefaultParameterValue(null)]T t); // error void Test2<T>([DefaultParameterValue(null)]T t) where T : C; // OK void Test3<T>([DefaultParameterValue(null)]T t) where T : class; // OK void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error } "; CreateCompilation(text).VerifyDiagnostics( // (6,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test1<T>([DefaultParameterValue(null)]T t); // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (9,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type1() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]object t); // CS1910 } "; CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type2() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]System.Type t); // CS1910 } "; CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1961ERR_UnexpectedVariance() { var text = @"interface Goo<out T> { T Bar(); void Baz(T t); }"; CreateCompilation(text).VerifyDiagnostics( // (4,14): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'Goo<T>.Baz(T)'. 'T' is covariant. // void Baz(T t); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("Goo<T>.Baz(T)", "T", "covariant", "contravariantly").WithLocation(4, 14)); } [Fact] public void CS1965ERR_DeriveFromDynamic() { var text = @"public class ErrorCode : dynamic { }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (1,26): error CS1965: 'ErrorCode': cannot derive from the dynamic type Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("ErrorCode")); } [Fact, WorkItem(552740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552740")] public void CS1966ERR_DeriveFromConstructedDynamic() { var text = @" interface I<T> { } class C<T> { public enum D { } } class E1 : I<dynamic> {} class E2 : I<C<dynamic>.D*[]> {} "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (11,12): error CS1966: 'E2': cannot implement a dynamic interface 'I<C<dynamic>.D*[]>' // class E2 : I<C<dynamic>.D*[]> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<C<dynamic>.D*[]>").WithArguments("E2", "I<C<dynamic>.D*[]>"), // (10,12): error CS1966: 'E1': cannot implement a dynamic interface 'I<dynamic>' // class E1 : I<dynamic> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<dynamic>").WithArguments("E1", "I<dynamic>")); } [Fact] public void CS1967ERR_DynamicTypeAsBound() { var source = @"delegate void D<T>() where T : dynamic;"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (1,32): error CS1967: Constraint cannot be the dynamic type Diagnostic(ErrorCode.ERR_DynamicTypeAsBound, "dynamic")); } [Fact] public void CS1968ERR_ConstructedDynamicTypeAsBound() { var source = @"interface I<T> { } struct S<T> { internal delegate void D<U>(); } class A<T> { } class B<T, U> where T : A<S<T>.D<dynamic>>, I<dynamic[]> where U : I<S<dynamic>.D<T>> { }"; CreateCompilation(source).VerifyDiagnostics( // (8,15): error CS1968: Constraint cannot be a dynamic type 'A<S<T>.D<dynamic>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "A<S<T>.D<dynamic>>").WithArguments("A<S<T>.D<dynamic>>").WithLocation(8, 15), // (8,35): error CS1968: Constraint cannot be a dynamic type 'I<dynamic[]>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<dynamic[]>").WithArguments("I<dynamic[]>").WithLocation(8, 35), // (9,15): error CS1968: Constraint cannot be a dynamic type 'I<S<dynamic>.D<T>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<S<dynamic>.D<T>>").WithArguments("I<S<dynamic>.D<T>>").WithLocation(9, 15)); } // Instead of CS1982 ERR_DynamicNotAllowedInAttribute we report CS0181 ERR_BadAttributeParamType [Fact] public void CS1982ERR_DynamicNotAllowedInAttribute_NoError() { var text = @" using System; public class C<T> { public enum D { A } } [A(T = typeof(dynamic[]))] // Dev11 reports error, but this should be ok [A(T = typeof(C<dynamic>))] [A(T = typeof(C<dynamic>[]))] [A(T = typeof(C<dynamic>.D[]))] [A(T = typeof(C<dynamic>.D*[]))] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class A : Attribute { public Type T; } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(); } [Fact] public void CS7021ERR_NamespaceNotAllowedInScript() { var text = @" namespace N1 { class A { public int Goo() { return 2; }} } "; var expectedDiagnostics = new[] { // (2,1): error CS7021: You cannot declare namespace in script code // namespace N1 Diagnostic(ErrorCode.ERR_NamespaceNotAllowedInScript, "namespace").WithLocation(2, 1) }; CreateCompilationWithMscorlib45(new[] { Parse(text, options: TestOptions.Script) }).VerifyDiagnostics(expectedDiagnostics); } [Fact] public void CS8050ERR_InitializerOnNonAutoProperty() { var source = @"public class C { int A { get; set; } = 1; int I { get { throw null; } set { } } = 1; static int S { get { throw null; } set { } } = 1; protected int P { get { throw null; } set { } } = 1; }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS8050: Only auto-implemented properties can have initializers. // int I { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "I").WithArguments("C.I").WithLocation(5, 9), // (6,16): error CS8050: Only auto-implemented properties can have initializers. // static int S { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "S").WithArguments("C.S").WithLocation(6, 16), // (7,19): error CS8050: Only auto-implemented properties can have initializers. // protected int P { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "P").WithArguments("C.P").WithLocation(7, 19) ); } [Fact] public void ErrorTypeCandidateSymbols1() { var text = @" class A { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.TypeWithAnnotations; Assert.Equal(SymbolKind.ErrorType, fieldType.Type.Kind); Assert.Equal("B", fieldType.Type.Name); var errorFieldType = (ErrorTypeSymbol)fieldType.Type; Assert.Equal(CandidateReason.None, errorFieldType.CandidateReason); Assert.Equal(0, errorFieldType.CandidateSymbols.Length); } [Fact] public void ErrorTypeCandidateSymbols2() { var text = @" class C { private class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single(); var classB = (NamedTypeSymbol)classC.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Inaccessible, errorFieldType.CandidateReason); Assert.Equal(1, errorFieldType.CandidateSymbols.Length); Assert.Equal(classB, errorFieldType.CandidateSymbols[0]); } [Fact] public void ErrorTypeCandidateSymbols3() { var text = @" using N1; using N2; namespace N1 { class B {} } namespace N2 { class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var ns1 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N1").Single(); var ns2 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N2").Single(); var classBinN1 = (NamedTypeSymbol)ns1.GetTypeMembers("B").Single(); var classBinN2 = (NamedTypeSymbol)ns2.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Ambiguous, errorFieldType.CandidateReason); Assert.Equal(2, errorFieldType.CandidateSymbols.Length); Assert.True((TypeSymbol.Equals(classBinN1, (TypeSymbol)errorFieldType.CandidateSymbols[0], TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(classBinN2, (TypeSymbol)errorFieldType.CandidateSymbols[1], TypeCompareKind.ConsiderEverything2)) || (TypeSymbol.Equals(classBinN2, (TypeSymbol)errorFieldType.CandidateSymbols[0], TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(classBinN1, (TypeSymbol)errorFieldType.CandidateSymbols[1], TypeCompareKind.ConsiderEverything2)), "CandidateSymbols must by N1.B and N2.B in some order"); } #endregion #region "Symbol Warning Tests" /// <summary> /// current error 104 /// </summary> [Fact] public void CS0105WRN_DuplicateUsing01() { var text = @"using System; using System; namespace Goo.Bar { class A { } } namespace testns { using Goo.Bar; using System; using Goo.Bar; class B : A { } }"; CreateCompilation(text).VerifyDiagnostics( // (2,7): warning CS0105: The using directive for 'System' appeared previously in this namespace // using System; Diagnostic(ErrorCode.WRN_DuplicateUsing, "System").WithArguments("System"), // (13,11): warning CS0105: The using directive for 'Goo.Bar' appeared previously in this namespace // using Goo.Bar; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Goo.Bar").WithArguments("Goo.Bar"), // (1,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (12,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (13,5): info CS8019: Unnecessary using directive. // using Goo.Bar; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Goo.Bar;")); // TODO... // var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0108WRN_NewRequired01() { var text = @"using System; namespace x { public class clx { public int i = 1; } public class cly : clx { public static int i = 2; // CS0108, use the new keyword public static void Main() { Console.WriteLine(i); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 27, IsWarning = true }); } [Fact] public void CS0108WRN_NewRequired02() { var source = @"class A { public static void P() { } public static void Q() { } public void R() { } public void S() { } public static int T { get; set; } public static int U { get; set; } public int V { get; set; } public int W { get; set; } } class B : A { public static int P { get; set; } // CS0108 public int Q { get; set; } // CS0108 public static int R { get; set; } // CS0108 public int S { get; set; } // CS0108 public static void T() { } // CS0108 public void U() { } // CS0108 public static void V() { } // CS0108 public void W() { } // CS0108 } "; CreateCompilation(source).VerifyDiagnostics( // (15,16): warning CS0108: 'B.Q' hides inherited member 'A.Q()'. Use the new keyword if hiding was intended. // public int Q { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "Q").WithArguments("B.Q", "A.Q()").WithLocation(15, 16), // (16,23): warning CS0108: 'B.R' hides inherited member 'A.R()'. Use the new keyword if hiding was intended. // public static int R { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "R").WithArguments("B.R", "A.R()").WithLocation(16, 23), // (17,16): warning CS0108: 'B.S' hides inherited member 'A.S()'. Use the new keyword if hiding was intended. // public int S { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "S").WithArguments("B.S", "A.S()").WithLocation(17, 16), // (18,24): warning CS0108: 'B.T()' hides inherited member 'A.T'. Use the new keyword if hiding was intended. // public static void T() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("B.T()", "A.T").WithLocation(18, 24), // (19,17): warning CS0108: 'B.U()' hides inherited member 'A.U'. Use the new keyword if hiding was intended. // public void U() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "U").WithArguments("B.U()", "A.U").WithLocation(19, 17), // (20,24): warning CS0108: 'B.V()' hides inherited member 'A.V'. Use the new keyword if hiding was intended. // public static void V() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "V").WithArguments("B.V()", "A.V").WithLocation(20, 24), // (21,17): warning CS0108: 'B.W()' hides inherited member 'A.W'. Use the new keyword if hiding was intended. // public void W() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "W").WithArguments("B.W()", "A.W").WithLocation(21, 17), // (14,23): warning CS0108: 'B.P' hides inherited member 'A.P()'. Use the new keyword if hiding was intended. // public static int P { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "P").WithArguments("B.P", "A.P()").WithLocation(14, 23)); } [WorkItem(539624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539624")] [Fact] public void CS0108WRN_NewRequired03() { var text = @" class BaseClass { public int MyMeth(int intI) { return intI; } } class MyClass : BaseClass { public static int MyMeth(int intI) // CS0108 { return intI + 1; } } class SBase { protected static void M() {} } class DClass : SBase { protected void M() {} // CS0108 } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 13, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 26, Column = 20, IsWarning = true }); } [WorkItem(540459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540459")] [Fact] public void CS0108WRN_NewRequired04() { var text = @" class A { public void f() { } } class B: A { } class C : B { public int f = 3; //CS0108 } "; CreateCompilation(text).VerifyDiagnostics( // (15,16): warning CS0108: 'C.f' hides inherited member 'A.f()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "f").WithArguments("C.f", "A.f()")); } [Fact] public void CS0108WRN_NewRequired05() { var text = @" class A { public static void SM1() { } public static void SM2() { } public static void SM3() { } public static void SM4() { } public void IM1() { } public void IM2() { } public void IM3() { } public void IM4() { } public static int SP1 { get; set; } public static int SP2 { get; set; } public static int SP3 { get; set; } public static int SP4 { get; set; } public int IP1 { get; set; } public int IP2 { get; set; } public int IP3 { get; set; } public int IP4 { get; set; } public static event System.Action SE1; public static event System.Action SE2; public static event System.Action SE3; public static event System.Action SE4; public event System.Action IE1{ add { } remove { } } public event System.Action IE2{ add { } remove { } } public event System.Action IE3{ add { } remove { } } public event System.Action IE4{ add { } remove { } } } class B : A { public static int SM1 { get; set; } //CS0108 public int SM2 { get; set; } //CS0108 public static event System.Action SM3; //CS0108 public event System.Action SM4{ add { } remove { } } //CS0108 public static int IM1 { get; set; } //CS0108 public int IM2 { get; set; } //CS0108 public static event System.Action IM3; //CS0108 public event System.Action IM4{ add { } remove { } } //CS0108 public static void SP1() { } //CS0108 public void SP2() { } //CS0108 public static event System.Action SP3; //CS0108 public event System.Action SP4{ add { } remove { } } //CS0108 public static void IP1() { } //CS0108 public void IP2() { } //CS0108 public static event System.Action IP3; //CS0108 public event System.Action IP4{ add { } remove { } } //CS0108 public static void SE1() { } //CS0108 public void SE2() { } //CS0108 public static int SE3 { get; set; } //CS0108 public int SE4 { get; set; } //CS0108 public static void IE1() { } //CS0108 public void IE2() { } //CS0108 public static int IE3 { get; set; } //CS0108 public int IE4 { get; set; } //CS0108 }"; CreateCompilation(text).VerifyDiagnostics( // (36,23): warning CS0108: 'B.SM1' hides inherited member 'A.SM1()'. Use the new keyword if hiding was intended. // public static int SM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM1").WithArguments("B.SM1", "A.SM1()"), // (37,16): warning CS0108: 'B.SM2' hides inherited member 'A.SM2()'. Use the new keyword if hiding was intended. // public int SM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM2").WithArguments("B.SM2", "A.SM2()"), // (38,39): warning CS0108: 'B.SM3' hides inherited member 'A.SM3()'. Use the new keyword if hiding was intended. // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM3").WithArguments("B.SM3", "A.SM3()"), // (39,32): warning CS0108: 'B.SM4' hides inherited member 'A.SM4()'. Use the new keyword if hiding was intended. // public event System.Action SM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM4").WithArguments("B.SM4", "A.SM4()"), // (41,23): warning CS0108: 'B.IM1' hides inherited member 'A.IM1()'. Use the new keyword if hiding was intended. // public static int IM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM1").WithArguments("B.IM1", "A.IM1()"), // (42,16): warning CS0108: 'B.IM2' hides inherited member 'A.IM2()'. Use the new keyword if hiding was intended. // public int IM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM2").WithArguments("B.IM2", "A.IM2()"), // (43,39): warning CS0108: 'B.IM3' hides inherited member 'A.IM3()'. Use the new keyword if hiding was intended. // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM3").WithArguments("B.IM3", "A.IM3()"), // (44,32): warning CS0108: 'B.IM4' hides inherited member 'A.IM4()'. Use the new keyword if hiding was intended. // public event System.Action IM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM4").WithArguments("B.IM4", "A.IM4()"), // (46,24): warning CS0108: 'B.SP1()' hides inherited member 'A.SP1'. Use the new keyword if hiding was intended. // public static void SP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP1").WithArguments("B.SP1()", "A.SP1"), // (47,17): warning CS0108: 'B.SP2()' hides inherited member 'A.SP2'. Use the new keyword if hiding was intended. // public void SP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP2").WithArguments("B.SP2()", "A.SP2"), // (48,39): warning CS0108: 'B.SP3' hides inherited member 'A.SP3'. Use the new keyword if hiding was intended. // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP3").WithArguments("B.SP3", "A.SP3"), // (49,32): warning CS0108: 'B.SP4' hides inherited member 'A.SP4'. Use the new keyword if hiding was intended. // public event System.Action SP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP4").WithArguments("B.SP4", "A.SP4"), // (51,24): warning CS0108: 'B.IP1()' hides inherited member 'A.IP1'. Use the new keyword if hiding was intended. // public static void IP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP1").WithArguments("B.IP1()", "A.IP1"), // (52,17): warning CS0108: 'B.IP2()' hides inherited member 'A.IP2'. Use the new keyword if hiding was intended. // public void IP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP2").WithArguments("B.IP2()", "A.IP2"), // (53,39): warning CS0108: 'B.IP3' hides inherited member 'A.IP3'. Use the new keyword if hiding was intended. // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP3").WithArguments("B.IP3", "A.IP3"), // (54,32): warning CS0108: 'B.IP4' hides inherited member 'A.IP4'. Use the new keyword if hiding was intended. // public event System.Action IP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP4").WithArguments("B.IP4", "A.IP4"), // (56,24): warning CS0108: 'B.SE1()' hides inherited member 'A.SE1'. Use the new keyword if hiding was intended. // public static void SE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE1").WithArguments("B.SE1()", "A.SE1"), // (57,17): warning CS0108: 'B.SE2()' hides inherited member 'A.SE2'. Use the new keyword if hiding was intended. // public void SE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE2").WithArguments("B.SE2()", "A.SE2"), // (58,23): warning CS0108: 'B.SE3' hides inherited member 'A.SE3'. Use the new keyword if hiding was intended. // public static int SE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE3").WithArguments("B.SE3", "A.SE3"), // (59,16): warning CS0108: 'B.SE4' hides inherited member 'A.SE4'. Use the new keyword if hiding was intended. // public int SE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE4").WithArguments("B.SE4", "A.SE4"), // (61,24): warning CS0108: 'B.IE1()' hides inherited member 'A.IE1'. Use the new keyword if hiding was intended. // public static void IE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE1").WithArguments("B.IE1()", "A.IE1"), // (62,17): warning CS0108: 'B.IE2()' hides inherited member 'A.IE2'. Use the new keyword if hiding was intended. // public void IE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE2").WithArguments("B.IE2()", "A.IE2"), // (63,23): warning CS0108: 'B.IE3' hides inherited member 'A.IE3'. Use the new keyword if hiding was intended. // public static int IE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE3").WithArguments("B.IE3", "A.IE3"), // (64,16): warning CS0108: 'B.IE4' hides inherited member 'A.IE4'. Use the new keyword if hiding was intended. // public int IE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE4").WithArguments("B.IE4", "A.IE4"), // (53,39): warning CS0067: The event 'B.IP3' is never used // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IP3").WithArguments("B.IP3"), // (25,39): warning CS0067: The event 'A.SE2' is never used // public static event System.Action SE2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE2").WithArguments("A.SE2"), // (26,39): warning CS0067: The event 'A.SE3' is never used // public static event System.Action SE3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE3").WithArguments("A.SE3"), // (38,39): warning CS0067: The event 'B.SM3' is never used // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SM3").WithArguments("B.SM3"), // (279): warning CS0067: The event 'A.SE4' is never used // public static event System.Action SE4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE4").WithArguments("A.SE4"), // (48,39): warning CS0067: The event 'B.SP3' is never used // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SP3").WithArguments("B.SP3"), // (24,39): warning CS0067: The event 'A.SE1' is never used // public static event System.Action SE1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE1").WithArguments("A.SE1"), // (43,39): warning CS0067: The event 'B.IM3' is never used // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IM3").WithArguments("B.IM3")); } [WorkItem(539624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539624")] [Fact] public void CS0108WRN_NewRequired_Arity() { var text = @" class Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } class HideWithClass : Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public class M { } public class M<A> { } public class M<A, B> { } public class M<A, B, C> { } public class D { } public class D<A> { } public class D<A, B> { } public class D<A, B, C> { } } class HideWithMethod : Class { public void T() { } public void T<A>() { } public void T<A, B>() { } public void T<A, B, C>() { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public void D() { } public void D<A>() { } public void D<A, B>() { } public void D<A, B, C>() { } } class HideWithDelegate : Class { public delegate void T(); public delegate void T<A>(); public delegate void T<A, B>(); public delegate void T<A, B, C>(); public delegate void M(); public delegate void M<A>(); public delegate void M<A, B>(); public delegate void M<A, B, C>(); public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } "; CreateCompilation(text).VerifyDiagnostics( /* HideWithClass */ // (22,18): warning CS0108: 'HideWithClass.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T", "Class.T"), // (23,18): warning CS0108: 'HideWithClass.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A>", "Class.T<A>"), // (24,18): warning CS0108: 'HideWithClass.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B>", "Class.T<A, B>"), // (25,18): warning CS0108: 'HideWithClass.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B, C>", "Class.T<A, B, C>"), // (27,18): warning CS0108: 'HideWithClass.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M", "Class.M()"), // (28,18): warning CS0108: 'HideWithClass.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A>", "Class.M<A>()"), // (29,18): warning CS0108: 'HideWithClass.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B>", "Class.M<A, B>()"), // (30,18): warning CS0108: 'HideWithClass.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B, C>", "Class.M<A, B, C>()"), // (32,18): warning CS0108: 'HideWithClass.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D", "Class.D"), // (33,18): warning CS0108: 'HideWithClass.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A>", "Class.D<A>"), // (34,18): warning CS0108: 'HideWithClass.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B>", "Class.D<A, B>"), // (35,18): warning CS0108: 'HideWithClass.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B, C>", "Class.D<A, B, C>"), /* HideWithMethod */ // (40,17): warning CS0108: 'HideWithMethod.T()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T()", "Class.T"), // (41,17): warning CS0108: 'HideWithMethod.T<A>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A>()", "Class.T"), // (42,17): warning CS0108: 'HideWithMethod.T<A, B>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B>()", "Class.T"), // (43,17): warning CS0108: 'HideWithMethod.T<A, B, C>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B, C>()", "Class.T"), // (45,17): warning CS0108: 'HideWithMethod.M()' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M()", "Class.M()"), // (46,17): warning CS0108: 'HideWithMethod.M<A>()' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A>()", "Class.M<A>()"), // (47,17): warning CS0108: 'HideWithMethod.M<A, B>()' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B>()", "Class.M<A, B>()"), // (48,17): warning CS0108: 'HideWithMethod.M<A, B, C>()' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B, C>()", "Class.M<A, B, C>()"), // (50,17): warning CS0108: 'HideWithMethod.D()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D()", "Class.D"), // (51,17): warning CS0108: 'HideWithMethod.D<A>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A>()", "Class.D"), // (52,17): warning CS0108: 'HideWithMethod.D<A, B>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B>()", "Class.D"), // (53,17): warning CS0108: 'HideWithMethod.D<A, B, C>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B, C>()", "Class.D"), /* HideWithDelegate */ // (58,26): warning CS0108: 'HideWithDelegate.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T", "Class.T"), // (59,26): warning CS0108: 'HideWithDelegate.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A>", "Class.T<A>"), // (60,26): warning CS0108: 'HideWithDelegate.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B>", "Class.T<A, B>"), // (61,26): warning CS0108: 'HideWithDelegate.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B, C>", "Class.T<A, B, C>"), // (63,26): warning CS0108: 'HideWithDelegate.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M", "Class.M()"), // (64,26): warning CS0108: 'HideWithDelegate.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A>", "Class.M<A>()"), // (65,26): warning CS0108: 'HideWithDelegate.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B>", "Class.M<A, B>()"), // (66,26): warning CS0108: 'HideWithDelegate.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B, C>", "Class.M<A, B, C>()"), // (68,26): warning CS0108: 'HideWithDelegate.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D", "Class.D"), // (69,26): warning CS0108: 'HideWithDelegate.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A>", "Class.D<A>"), // (70,26): warning CS0108: 'HideWithDelegate.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B>", "Class.D<A, B>"), // (71,26): warning CS0108: 'HideWithDelegate.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B, C>", "Class.D<A, B, C>")); } [Fact, WorkItem(546736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546736")] public void CS0108WRN_NewRequired_Partial() { var text = @" partial class Parent { partial void PM(int x); private void M(int x) { } partial class Child : Parent { partial void PM(int x); private void M(int x) { } } } partial class AnotherChild : Parent { partial void PM(int x); private void M(int x) { } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_NewRequired, "PM").WithArguments("Parent.Child.PM(int)", "Parent.PM(int)"), Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Parent.Child.M(int)", "Parent.M(int)")); } [Fact] public void CS0109WRN_NewNotRequired() { var text = @"namespace x { public class a { public int i; } public class b : a { public new int i; public new int j; // CS0109 public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewNotRequired, Line = 11, Column = 24, IsWarning = true }); } [Fact] public void CS0114WRN_NewOrOverrideExpected() { var text = @"abstract public class clx { public abstract void f(); } public class cly : clx { public void f() // CS0114, hides base class member { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 8, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 14 } }); } [Fact] public void CS0282WRN_SequentialOnPartialClass() { var text = @" partial struct A { int i; } partial struct A { int j; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'A'. To specify an ordering, all instance fields must be in the same declaration. // partial struct A Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "A").WithArguments("A"), // (3,9): warning CS0169: The field 'A.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("A.i"), // (7,9): warning CS0169: The field 'A.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("A.j")); } [Fact] [WorkItem(23668, "https://github.com/dotnet/roslyn/issues/23668")] public void CS0282WRN_PartialWithPropertyButSingleField() { string program = @"partial struct X // No warning CS0282 { // The only field of X is a backing field of A. public int A { get; set; } } partial struct X : I { // This partial definition has no field. int I.A { get => A; set => A = value; } } interface I { int A { get; set; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics(); } /// <summary> /// import - Lib: class A { class B {} } /// vs. curr: Namespace A { class B {} } - use B /// </summary> [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS0435WRN_SameFullNameThisNsAgg01() { var text = @"namespace CSFields { public class FFF { } } namespace SA { class Test { CSFields.FFF var = null; void M(CSFields.FFF p) { } } } "; // class CSFields { class FFF {}} var ref1 = TestReferences.SymbolsTests.Fields.CSFields.dll; var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // void M(CSFields.FFF p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,9): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,22): warning CS0414: The field 'SA.Test.var' is assigned but its value is never used // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "var").WithArguments("SA.Test.var") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } /// <summary> /// import - Lib: class A {} vs. curr: class A { } /// </summary> [Fact] public void CS0436WRN_SameFullNameThisAggAgg01() { var text = @"class Class1 { } namespace SA { class Test { Class1 cls; void M(Class1 p) { } } } "; // Class1 var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // Roslyn gives CS1542 or CS0104 var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (8,16): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(Class1 p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,9): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Class1 cls; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,16): warning CS0169: The field 'SA.Test.cls' is never used // Class1 cls; Diagnostic(ErrorCode.WRN_UnreferencedField, "cls").WithArguments("SA.Test.cls")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [Fact] [WorkItem(546077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546077")] public void MultipleSymbolDisambiguation() { var sourceRef1 = @" public class CCC { public class X { } } public class CNC { public class X { } } namespace NCC { public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } public class CNN { public class X { } } namespace NCN { public class X { } } namespace NNN { public class X { } } "; var sourceRef2 = @" public class CCC { public class X { } } namespace CNC { public class X { } } public class NCC{ public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } namespace CNN { public class X { } } public class NCN { public class X { } } namespace NNN { public class X { } } "; var sourceLib = @" public class CCC { public class X { } } namespace CCN { public class X { } } public class CNC { public class X { } } namespace CNN { public class X { } } public class NCC { public class X { } } namespace NCN { public class X { } } public class NNC { public class X { } } namespace NNN { public class X { } } internal class DC : CCC.X { } internal class DN : CCN.X { } internal class D3 : CNC.X { } internal class D4 : CNN.X { } internal class D5 : NCC.X { } internal class D6 : NCN.X { } internal class D7 : NNC.X { } internal class D8 : NNN.X { } "; var ref1 = CreateCompilation(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilation(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilation(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // In some cases we might order the symbols differently than Dev11 and thus reporting slightly different warnings. // E.g. (src:type, md:type, md:namespace) vs (src:type, md:namespace, md:type) // We report (type, type) ambiguity while Dev11 reports (type, namespace) ambiguity, but both are equally correct. // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. lib.VerifyDiagnostics( // C:\lib.cs(12,21): warning CS0435: The namespace 'CCN' in 'C:\lib.cs' conflicts with the imported type 'CCN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CCN").WithArguments(@"C:\lib.cs", "CCN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCN"), // C:\lib.cs(16,21): warning CS0435: The namespace 'NCN' in 'C:\lib.cs' conflicts with the imported type 'NCN' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "NCN").WithArguments(@"C:\lib.cs", "NCN", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN"), // C:\lib.cs(16,25): warning CS0436: The type 'NCN.X' in 'C:\lib.cs' conflicts with the imported type 'NCN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NCN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN.X"), // C:\lib.cs(11,21): warning CS0436: The type 'CCC' in 'C:\lib.cs' conflicts with the imported type 'CCC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CCC").WithArguments(@"C:\lib.cs", "CCC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCC"), // C:\lib.cs(15,21): warning CS0436: The type 'NCC' in 'C:\lib.cs' conflicts with the imported type 'NCC' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "NCC").WithArguments(@"C:\lib.cs", "NCC", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCC"), // C:\lib.cs(13,21): warning CS0436: The type 'CNC' in 'C:\lib.cs' conflicts with the imported type 'CNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CNC").WithArguments(@"C:\lib.cs", "CNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNC"), // C:\lib.cs(14,21): warning CS0435: The namespace 'CNN' in 'C:\lib.cs' conflicts with the imported type 'CNN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CNN").WithArguments(@"C:\lib.cs", "CNN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN"), // C:\lib.cs(14,25): warning CS0436: The type 'CNN.X' in 'C:\lib.cs' conflicts with the imported type 'CNN.X' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "CNN.X", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN.X"), // C:\lib.cs(17,21): warning CS0437: The type 'NNC' in 'C:\lib.cs' conflicts with the imported namespace 'NNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "NNC").WithArguments(@"C:\lib.cs", "NNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNC"), // C:\lib.cs(18,25): warning CS0436: The type 'NNN.X' in 'C:\lib.cs' conflicts with the imported type 'NNN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NNN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNN.X")); } [Fact] public void MultipleSourceSymbols1() { var sourceLib = @" public class C { } namespace C { } public class D : C { }"; // do not report lookup errors CreateCompilation(sourceLib).VerifyDiagnostics( // error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [Fact] public void MultipleSourceSymbols2() { var sourceRef1 = @" public class C { public class X { } } "; var sourceRef2 = @" namespace N { public class X { } } "; var sourceLib = @" public class C { public class X { } } namespace C { public class X { } } internal class D : C.X { } "; var ref1 = CreateCompilation(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilation(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilation(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // do not report lookup errors lib.VerifyDiagnostics( // C:\lib.cs(2,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [WorkItem(545725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545725")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg02() { var text = @" namespace System { class Int32 { const Int32 MaxValue = null; static void Main() { Int32 x = System.Int32.MaxValue; } } } "; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }).VerifyDiagnostics( // goo.cs(6,15): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,13): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,23): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "System.Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,19): warning CS0219: The variable 'x' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg03() { var text = @"namespace System { class Object { static void Main() { Console.WriteLine(""hello""); } } class Goo : object {} class Bar : Object {} }"; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }).VerifyDiagnostics( // goo.cs(11,17): warning CS0436: The type 'System.Object' in 'goo.cs' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("goo.cs", "System.Object", RuntimeCorLibName.FullName, "object")); } /// <summary> /// import- Lib: namespace A { class B{} } vs. curr: class A { class B {} } /// </summary> [Fact] public void CS0437WRN_SameFullNameThisAggNs01() { var text = @"public class AppCS { public class App { } } namespace SA { class Test { AppCS.App app = null; void M(AppCS.App p) { } } } "; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var cs00 = TestReferences.MetadataTests.NetModule01.ModuleCS00; var cs01 = TestReferences.MetadataTests.NetModule01.ModuleCS01; var vb01 = TestReferences.MetadataTests.NetModule01.ModuleVB01; var ref1 = TestReferences.MetadataTests.NetModule01.AppCS; // Roslyn CS1542 var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(AppCS.App p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,9): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // AppCS.App app = null; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,19): warning CS0414: The field 'SA.Test.app' is assigned but its value is never used // AppCS.App app = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "app").WithArguments("SA.Test.app")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [WorkItem(545649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545649")] [Fact] public void CS0437WRN_SameFullNameThisAggNs02() { var source = @" using System; class System { } "; // NOTE: both mscorlib.dll and System.Core.dll define types in the System namespace. var compilation = CreateCompilation( Parse(source, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", RuntimeCorLibName.FullName, "System"), // (2,7): error CS0138: A using namespace directive can only be applied to namespaces; 'System' is a type not a namespace // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [Fact] public void CS0465WRN_FinalizeMethod() { var text = @" class A { protected virtual void Finalize() {} // CS0465 } abstract class B { public abstract void Finalize(); // CS0465 } abstract class C { protected int Finalize() {return 0;} // No Warning protected abstract void Finalize(int x); // No Warning protected virtual void Finalize<T>() { } // No Warning } class D : C { protected override void Finalize(int x) { } // No Warning protected override void Finalize<U>() { } // No Warning }"; CreateCompilation(text).VerifyDiagnostics( // (4,27): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (9,25): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [Fact] public void CS0473WRN_ExplicitImplCollision() { var text = @"public interface ITest<T> { int TestMethod(int i); int TestMethod(T i); } public class ImplementingClass : ITest<int> { int ITest<int>.TestMethod(int i) // CS0473 { return i + 1; } public int TestMethod(int i) { return i - 1; } } class T { static int Main() { return 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 9, Column = 20, IsWarning = true }); } [Fact] public void CS0626WRN_ExternMethodNoImplementation01() { var source = @"class A : System.Attribute { } class B { extern void M(); extern object P1 { get; set; } extern static public bool operator !(B b); } class C { [A] extern void M(); [A] extern object P1 { get; set; } [A] extern static public bool operator !(C c); }"; CreateCompilation(source).VerifyDiagnostics( // (4,17): warning CS0626: Method, operator, or accessor 'B.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("B.M()").WithLocation(4, 17), // (5,24): warning CS0626: Method, operator, or accessor 'B.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("B.P1.get").WithLocation(5, 24), // (5,29): warning CS0626: Method, operator, or accessor 'B.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("B.P1.set").WithLocation(5, 29), // (6,40): warning CS0626: Method, operator, or accessor 'B.operator !(B)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "!").WithArguments("B.operator !(B)").WithLocation(6, 40), // (11,28): warning CS0626: Method, operator, or accessor 'C.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.P1.get").WithLocation(11, 28), // (11,33): warning CS0626: Method, operator, or accessor 'C.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("C.P1.set").WithLocation(11, 33)); } [WorkItem(544660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544660")] [WorkItem(530324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530324")] [Fact] public void CS0626WRN_ExternMethodNoImplementation02() { var source = @"class A : System.Attribute { } delegate void D(); class C { extern event D E1; [A] extern event D E2; }"; CreateCompilation(source).VerifyDiagnostics( // (5,20): warning CS0626: Method, operator, or accessor 'C.E1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event D E1; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E1").WithArguments("C.E1.remove").WithLocation(5, 20), // (6,24): warning CS0626: Method, operator, or accessor 'C.E2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // [A] extern event D E2; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E2").WithArguments("C.E2.remove").WithLocation(6, 24)); } [Fact] public void CS0628WRN_ProtectedInSealed01() { var text = @"namespace NS { sealed class Goo { protected int i = 0; protected internal void M() { } } sealed public class Bar<T> { internal protected void M1(T t) { } protected V M2<V>(T t) { return default(V); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 5, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 6, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 11, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 12, Column = 21, IsWarning = true }); } [Fact] public void CS0628WRN_ProtectedInSealed02() { var text = @"sealed class C { protected object P { get { return null; } } public int Q { get; protected set; } } sealed class C<T> { internal protected T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 3, Column = 22, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 4, Column = 35, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 45, IsWarning = true }); } [WorkItem(539588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539588")] [Fact] public void CS0628WRN_ProtectedInSealed03() { var text = @"abstract class C { protected abstract void M(); protected internal virtual int P { get { return 0; } } } sealed class D : C { protected override void M() { } protected internal override int P { get { return 0; } } protected void N() { } // CS0628 protected internal int Q { get { return 0; } } // CS0628 protected class Nested {} // CS0628 } "; CreateCompilation(text).VerifyDiagnostics( // (13,21): warning CS0628: 'D.Nested': new protected member declared in sealed type // protected class Nested {} // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Nested").WithArguments("D.Nested"), // (11,28): warning CS0628: 'D.Q': new protected member declared in sealed type // protected internal int Q { get { return 0; } } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Q").WithArguments("D.Q"), // (10,20): warning CS0628: 'D.N()': new protected member declared in sealed type // protected void N() { } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "N").WithArguments("D.N()") ); } [Fact] public void CS0628WRN_ProtectedInSealed04() { var text = @" sealed class C { protected event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (4,35): warning CS0628: 'C.E': new protected member declared in sealed type // protected event System.Action E; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "E").WithArguments("C.E"), // (4,35): warning CS0067: The event 'C.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0628WRN_ProtectedInSealed05() { const string text = @" abstract class C { protected C() { } } sealed class D : C { protected override D() { } protected D(byte b) { } protected internal D(short s) { } internal protected D(int i) { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,24): error CS0106: The modifier 'override' is not valid for this item // protected override D() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "D").WithArguments("override").WithLocation(9, 24), // (10,15): warning CS0628: 'D.D(byte)': new protected member declared in sealed type // protected D(byte b) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(byte)").WithLocation(10, 15), // (11,24): warning CS0628: 'D.D(short)': new protected member declared in sealed type // protected internal D(short s) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(short)").WithLocation(11, 24), // (12,24): warning CS0628: 'D.D(int)': new protected member declared in sealed type // internal protected D(int i) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(int)").WithLocation(12, 24)); } [Fact] public void CS0659WRN_EqualsWithoutGetHashCode() { var text = @"class Test { public override bool Equals(object o) { return true; } // CS0659 } // However the warning should NOT be produced if the Equals is not a 'real' override // of Equals. Neither of these should produce a warning: class Test2 { public new virtual bool Equals(object o) { return true; } } class Test3 : Test2 { public override bool Equals(object o) { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals() { var text = @" class TestBase { public new virtual bool Equals(object o) { return true; } } class Test : TestBase // CS0660 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } // This does not count! public override bool Equals(object o) { return true; } public override int GetHashCode() { return 0; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,7): warning CS0660: 'Test' defines operator == or operator != but does not override Object.Equals(object o) Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "Test").WithArguments("Test")); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals_NoWarningWhenOverriddenWithDynamicParameter() { string source = @" public class C { public override bool Equals(dynamic o) { return false; } public static bool operator ==(C v1, C v2) { return true; } public static bool operator !=(C v1, C v2) { return false; } public override int GetHashCode() { return base.GetHashCode(); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0661WRN_EqualityOpWithoutGetHashCode() { var text = @" class TestBase { // This does not count; it has to be overridden on Test. public override int GetHashCode() { return 123; } } class Test : TestBase // CS0661 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } public override bool Equals(object o) { return true; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test"), // (7,7): warning CS0661: 'Test' defines operator == or operator != but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact()] public void CS0672WRN_NonObsoleteOverridingObsolete() { var text = @"class MyClass { [System.Obsolete] public virtual void ObsoleteMethod() { } } class MyClass2 : MyClass { public override void ObsoleteMethod() // CS0672 { } } class MainClass { static public void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NonObsoleteOverridingObsolete, Line = 11, Column = 26, IsWarning = true }); } [Fact()] public void CS0684WRN_CoClassWithoutComImport() { var text = @" using System.Runtime.InteropServices; [CoClass(typeof(C))] // CS0684 interface I { } class C { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CoClassWithoutComImport, Line = 4, Column = 2, IsWarning = true }); } [Fact()] public void CS0809WRN_ObsoleteOverridingNonObsolete() { var text = @"public class Base { public virtual void Test1() { } } public class C : Base { [System.Obsolete()] public override void Test1() // CS0809 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ObsoleteOverridingNonObsolete, Line = 10, Column = 26, IsWarning = true }); } [Fact] public void CS0824WRN_ExternCtorNoImplementation01() { var source = @"namespace NS { public class C<T> { extern C(); struct S { extern S(string s); } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,16): warning CS0824: Constructor 'NS.C<T>.C()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("NS.C<T>.C()").WithLocation(5, 16), // (9,20): warning CS0824: Constructor 'NS.C<T>.S.S(string)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "S").WithArguments("NS.C<T>.S.S(string)").WithLocation(9, 20)); } [WorkItem(540859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540859")] [Fact] public void CS0824WRN_ExternCtorNoImplementation02() { var source = @"class A : System.Attribute { } class B { extern static B(); } class C { [A] extern static C(); }"; CreateCompilation(source).VerifyDiagnostics( // (4,19): warning CS0824: Constructor 'B.B()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(4, 19)); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation03() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B(); } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(comp, verify: Verification.Skipped). VerifyDiagnostics( // (8,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(8, 17) ); var methods = verifier.TestData.GetMethodsByName().Keys; Assert.True(methods.Any(n => n.StartsWith("A..ctor", StringComparison.Ordinal))); Assert.False(methods.Any(n => n.StartsWith("B..ctor", StringComparison.Ordinal))); // Haven't tried to emit it } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation04() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation05() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(unknown); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(unknown); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation06() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(1) {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation07() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation08() { var source = @" public class B { private int x = 1; public extern B(); }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyEmitDiagnostics( // (5,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(5, 17), // (4,15): warning CS0414: The field 'B.x' is assigned but its value is never used // private int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("B.x").WithLocation(4, 15) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation09() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base(); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base(); // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation10() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base() {} // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation01() { // Slight change from the native compiler; in the native compiler the "int" gets the green squiggle. // This seems wrong; the error should either highlight the parameter "x" or the initializer " = 2". // I see no reason to highlight the "int". I've changed it to highlight the "x". var compilation = CreateCompilation( @"interface IFace { int Goo(int x = 1); } class B : IFace { int IFace.Goo(int x = 2) { return 0; } }"); compilation.VerifyDiagnostics( // (7,23): error CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithLocation(7, 23).WithArguments("x")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation02() { var compilation = CreateCompilation( @"interface I { object this[string index = null] { get; } //CS1066 object this[char c, char d] { get; } //CS1066 } class C : I { object I.this[string index = ""apple""] { get { return null; } } //CS1066 internal object this[int x, int y = 0] { get { return null; } } //fine object I.this[char c = 'c', char d = 'd'] { get { return null; } } //CS1066 x2 } "); compilation.VerifyDiagnostics( // (3,24): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (7,26): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (10,24): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (10,38): warning CS1066: The default value specified for parameter 'd' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "d").WithArguments("d")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation03() { var compilation = CreateCompilation( @" class C { public static C operator!(C c = null) { return c; } public static implicit operator int(C c = null) { return 0; } } "); compilation.VerifyDiagnostics( // (4,33): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static C operator!(C c = null) { return c; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (5,43): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static implicit operator int(C c = null) { return 0; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c") ); } // public void CS1698WRN_AssumedMatchThis() => Move to CommandLineTest [Fact] public void CS1699WRN_UseSwitchInsteadOfAttribute_RoslynWRN73() { var text = @" [assembly:System.Reflection.AssemblyDelaySign(true)] // CS1699 "; // warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'System.Reflection.AssemblyDelaySign' // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute, @"/delaysign").WithArguments(@"/delaysign", "System.Reflection.AssemblyDelaySign") // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given CreateCompilation(text).VerifyDiagnostics( // warning CS73: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); } [Fact(), WorkItem(544447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544447")] public void CS1700WRN_InvalidAssemblyName() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""' '"")] // ok [assembly: InternalsVisibleTo(""\t\r\n;a"")] // ok (whitespace escape) [assembly: InternalsVisibleTo(""\u1234;a"")] // ok (assembly name Unicode escape) [assembly: InternalsVisibleTo(""' a '"")] // ok [assembly: InternalsVisibleTo(""\u1000000;a"")] // invalid escape [assembly: InternalsVisibleTo(""a'b'c"")] // quotes in the middle [assembly: InternalsVisibleTo(""Test, PublicKey=Null"")] [assembly: InternalsVisibleTo(""Test, Bar"")] [assembly: InternalsVisibleTo(""Test, Version"")] [assembly: InternalsVisibleTo(""app2, Retargetable=f"")] // CS1700 "; // Tested against Dev12 CreateCompilation(text).VerifyDiagnostics( // (8,12): warning CS1700: Assembly reference 'a'b'c' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""a'b'c"")").WithArguments("a'b'c").WithLocation(8, 12), // (9,12): warning CS1700: Assembly reference 'Test, PublicKey=Null' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, PublicKey=Null"")").WithArguments("Test, PublicKey=Null").WithLocation(9, 12), // (10,12): warning CS1700: Assembly reference 'Test, Bar' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Bar"")").WithArguments("Test, Bar").WithLocation(10, 12), // (11,12): warning CS1700: Assembly reference 'Test, Version' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Version"")").WithArguments("Test, Version").WithLocation(11, 12), // (12,12): warning CS1700: Assembly reference 'app2, Retargetable=f' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""app2, Retargetable=f"")").WithArguments("app2, Retargetable=f").WithLocation(12, 12)); } // CS1701WRN_UnifyReferenceMajMin --> ReferenceManagerTests [Fact] public void CS1956WRN_MultipleRuntimeImplementationMatches() { var text = @"class Base<T, S> { public virtual int Test(out T x) // CS1956 { x = default(T); return 0; } public virtual int Test(ref S x) { return 1; } } interface IFace { int Test(out int x); } class Derived : Base<int, int>, IFace { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeImplementationMatches, Line = 20, Column = 33, IsWarning = true }); } [Fact] public void CS1957WRN_MultipleRuntimeOverrideMatches() { var text = @"class Base<TString> { public virtual void Test(TString s, out int x) { x = 0; } public virtual void Test(string s, ref int x) { } // CS1957 } class Derived : Base<string> { public override void Test(string s, ref int x) { } } "; // We no longer report a runtime ambiguous override (CS1957) because the compiler produces a methodimpl record to disambiguate. CSharpCompilation comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation) { comp.VerifyDiagnostics( ); } else { comp.VerifyDiagnostics( // (8,25): warning CS1957: Member 'Derived.Test(string, ref int)' overrides 'Base<string>.Test(string, ref int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void Test(string s, ref int x) { } // CS1957 Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "Test").WithArguments("Base<string>.Test(string, ref int)", "Derived.Test(string, ref int)").WithLocation(8, 25) ); } } [Fact] public void CS3000WRN_CLS_NoVarArgs() { var text = @" [assembly: System.CLSCompliant(true)] public class Test { public void AddABunchOfInts( __arglist) { } // CS3000 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): warning CS3000: Methods with variable arguments are not CLS-compliant // public void AddABunchOfInts( __arglist) { } // CS3000 Diagnostic(ErrorCode.WRN_CLS_NoVarArgs, "AddABunchOfInts")); } [Fact] public void CS3001WRN_CLS_BadArgType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public void bad(ushort i) // CS3001 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,28): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void bad(ushort i) // CS3001 Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i").WithArguments("ushort")); } [Fact] public void CS3002WRN_CLS_BadReturnType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort bad() // CS3002, public method { return ushort.MaxValue; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,19): warning CS3002: Return type of 'a.bad()' is not CLS-compliant // public ushort bad() // CS3002, public method Diagnostic(ErrorCode.WRN_CLS_BadReturnType, "bad").WithArguments("a.bad()")); } [Fact] public void CS3003WRN_CLS_BadFieldPropType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort a1; // CS3003, public variable public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,19): warning CS3003: Type of 'a.a1' is not CLS-compliant // public ushort a1; // CS3003, public variable Diagnostic(ErrorCode.WRN_CLS_BadFieldPropType, "a1").WithArguments("a.a1")); } [Fact] public void CS3005WRN_CLS_BadIdentifierCase() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int a1 = 0; public static int A1 = 1; // CS3005 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,23): warning CS3005: Identifier 'a.A1' differing only in case is not CLS-compliant // public static int A1 = 1; // CS3005 Diagnostic(ErrorCode.WRN_CLS_BadIdentifierCase, "A1").WithArguments("a.A1")); } [Fact] public void CS3006WRN_CLS_OverloadRefOut() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyClass { public void f(int i) { } public void f(ref int i) // CS3006 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): warning CS3006: Overloaded method 'MyClass.f(ref int)' differing only in ref or out, or in array rank, is not CLS-compliant // public void f(ref int i) // CS3006 Diagnostic(ErrorCode.WRN_CLS_OverloadRefOut, "f").WithArguments("MyClass.f(ref int)")); } [Fact] public void CS3007WRN_CLS_OverloadUnnamed() { var text = @"[assembly: System.CLSCompliant(true)] public struct S { public void F(int[][] array) { } public void F(byte[][] array) { } // CS3007 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): warning CS3007: Overloaded method 'S.F(byte[][])' differing only by unnamed array types is not CLS-compliant // public void F(byte[][] array) { } // CS3007 Diagnostic(ErrorCode.WRN_CLS_OverloadUnnamed, "F").WithArguments("S.F(byte[][])")); } [Fact] public void CS3008WRN_CLS_BadIdentifier() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int _a = 0; // CS3008 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,23): warning CS3008: Identifier '_a' is not CLS-compliant // public static int _a = 0; // CS3008 Diagnostic(ErrorCode.WRN_CLS_BadIdentifier, "_a").WithArguments("_a")); } [Fact] public void CS3009WRN_CLS_BadBase() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class B { } public class C : B // CS3009 { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,14): warning CS3009: 'C': base type 'B' is not CLS-compliant // public class C : B // CS3009 Diagnostic(ErrorCode.WRN_CLS_BadBase, "C").WithArguments("C", "B")); } [Fact] public void CS3010WRN_CLS_BadInterfaceMember() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I { [CLSCompliant(false)] int M(); // CS3010 } public class C : I { public int M() { return 1; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): warning CS3010: 'I.M()': CLS-compliant interfaces must have only CLS-compliant members // int M(); // CS3010 Diagnostic(ErrorCode.WRN_CLS_BadInterfaceMember, "M").WithArguments("I.M()")); } [Fact] public void CS3011WRN_CLS_NoAbstractMembers() { var text = @"using System; [assembly: CLSCompliant(true)] public abstract class I { [CLSCompliant(false)] public abstract int M(); // CS3011 } public class C : I { public override int M() { return 1; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,25): warning CS3011: 'I.M()': only CLS-compliant members can be abstract // public abstract int M(); // CS3011 Diagnostic(ErrorCode.WRN_CLS_NoAbstractMembers, "M").WithArguments("I.M()")); } [Fact] public void CS3012WRN_CLS_NotOnModules() { var text = @"[module: System.CLSCompliant(true)] // CS3012 public class C { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (1,10): warning CS3012: You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking // [module: System.CLSCompliant(true)] // CS3012 Diagnostic(ErrorCode.WRN_CLS_NotOnModules, "System.CLSCompliant(true)")); } [Fact] public void CS3013WRN_CLS_ModuleMissingCLS() { var netModule = CreateEmptyCompilation("", options: TestOptions.ReleaseModule, assemblyName: "lib").EmitToImageReference(expectedWarnings: new[] { Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion) }); CreateCompilation("[assembly: System.CLSCompliant(true)]", new[] { netModule }).VerifyDiagnostics( // lib.netmodule: warning CS3013: Added modules must be marked with the CLSCompliant attribute to match the assembly Diagnostic(ErrorCode.WRN_CLS_ModuleMissingCLS)); } [Fact] public void CS3014WRN_CLS_AssemblyNotCLS() { var text = @"using System; // [assembly:CLSCompliant(true)] public class I { [CLSCompliant(true)] // CS3014 public void M() { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,17): warning CS3014: 'I.M()' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute // public void M() Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS, "M").WithArguments("I.M()")); } [Fact] public void CS3015WRN_CLS_BadAttributeType() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyAttribute : Attribute { public MyAttribute(int[] ai) { } // CS3015 } "; CreateCompilation(text).VerifyDiagnostics( // (4,14): warning CS3015: 'MyAttribute' has no accessible constructors which use only CLS-compliant types // public class MyAttribute : Attribute Diagnostic(ErrorCode.WRN_CLS_BadAttributeType, "MyAttribute").WithArguments("MyAttribute")); } [Fact] public void CS3016WRN_CLS_ArrayArgumentToAttribute() { var text = @"using System; [assembly: CLSCompliant(true)] [C(new int[] { 1, 2 })] // CS3016 public class C : Attribute { public C() { } public C(int[] a) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,2): warning CS3016: Arrays as attribute arguments is not CLS-compliant // [C(new int[] { 1, 2 })] // CS3016 Diagnostic(ErrorCode.WRN_CLS_ArrayArgumentToAttribute, "C(new int[] { 1, 2 })")); } [Fact] public void CS3017WRN_CLS_NotOnModules2() { var text = @"using System; [module: CLSCompliant(true)] [assembly: CLSCompliant(false)] // CS3017 class C { static void Main() { } } "; // NOTE: unlike dev11, roslyn assumes that [assembly:CLSCompliant(false)] means // "suppress all CLS diagnostics". CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS3018WRN_CLS_IllegalTrueInFalse() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class Outer { [CLSCompliant(true)] // CS3018 public class Nested { } [CLSCompliant(false)] public class Nested3 { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,18): warning CS3018: 'Outer.Nested' cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type 'Outer' // public class Nested { } Diagnostic(ErrorCode.WRN_CLS_IllegalTrueInFalse, "Nested").WithArguments("Outer.Nested", "Outer")); } [Fact] public void CS3019WRN_CLS_MeaninglessOnPrivateType() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] // CS3019 class C { [CLSCompliant(false)] // CS3019 void Test() { } static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,7): warning CS3019: CLS compliance checking will not be performed on 'C' because it is not visible from outside this assembly // class C Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "C").WithArguments("C"), // (7,10): warning CS3019: CLS compliance checking will not be performed on 'C.Test()' because it is not visible from outside this assembly // void Test() Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "Test").WithArguments("C.Test()")); } [Fact] public void CS3021WRN_CLS_AssemblyNotCLS2() { var text = @"using System; [CLSCompliant(false)] // CS3021 public class C { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,14): warning CS3021: 'C' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute // public class C Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS2, "C").WithArguments("C")); } [Fact] public void CS3022WRN_CLS_MeaninglessOnParam() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] public class C { public void F([CLSCompliant(true)] int i) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,20): warning CS3022: CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead. // public void F([CLSCompliant(true)] int i) Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnParam, "CLSCompliant(true)")); } [Fact] public void CS3023WRN_CLS_MeaninglessOnReturn() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { [return: System.CLSCompliant(true)] // CS3023 public static int Main() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,14): warning CS3023: CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead. // [return: System.CLSCompliant(true)] // CS3023 Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnReturn, "System.CLSCompliant(true)")); } [Fact] public void CS3024WRN_CLS_BadTypeVar() { var text = @"[assembly: System.CLSCompliant(true)] [type: System.CLSCompliant(false)] public class TestClass // CS3024 { public ushort us; } [type: System.CLSCompliant(false)] public interface ITest // CS3024 { } public interface I<T> where T : TestClass { } public class TestClass_2<T> where T : ITest { } public class TestClass_3<T> : I<T> where T : TestClass { } public class TestClass_4<T> : TestClass_2<T> where T : ITest { } public class Test { public static int Main() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,20): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public interface I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass"), // (13,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (17,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_4<T> : TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (15,26): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public class TestClass_3<T> : I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass")); } [Fact] public void CS3026WRN_CLS_VolatileField() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { public volatile int v0 = 0; // CS3026 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_VolatileField, Line = 4, Column = 25, IsWarning = true }); } [Fact] public void CS3027WRN_CLS_BadInterface() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I1 { } [CLSCompliant(false)] public interface I2 { } public interface I : I1, I2 { } public class Goo { static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_BadInterface, Line = 13, Column = 18, IsWarning = true }); } #endregion #region "Regressions or Mixed errors" [Fact] // bug 1985 public void ConstructWithErrors() { var text = @" class Base<T>{} class Derived : Base<NotFound>{}"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 22 }); var derived = comp.SourceModule.GlobalNamespace.GetTypeMembers("Derived").Single(); var Base = derived.BaseType(); Assert.Equal(TypeKind.Class, Base.TypeKind); } [Fact] // bug 3045 public void AliasQualifiedName00() { var text = @"using NSA = A; namespace A { class Goo { } } namespace B { class Test { class NSA { public NSA(int Goo) { this.Goo = Goo; } int Goo; } static int Main() { NSA::Goo goo = new NSA::Goo(); // shouldn't error here goo = Xyzzy; return 0; } static NSA::Goo Xyzzy = null; // shouldn't error here } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; var test = b.GetMembers("Test").Single() as NamedTypeSymbol; var nsa = test.GetMembers("NSA").Single() as NamedTypeSymbol; Assert.Equal(2, nsa.GetMembers().Length); } [WorkItem(538218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538218")] [Fact] public void RecursiveInterfaceLookup01() { var text = @"interface A<T> { } interface B : A<B.Garbage> { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DottedTypeNameNotFoundInAgg, Line = 2, Column = 19 }); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; } [WorkItem(538150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538150")] [Fact] public void CS0102ERR_DuplicateNameInClass04() { var text = @" namespace NS { struct MyType { public class MyMeth { } public void MyMeth() { } public int MyMeth; } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (8,21): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public void MyMeth() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public int MyMeth; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): warning CS0649: Field 'NS.MyType.MyMeth' is never assigned to, and will always have its default value 0 // public int MyMeth; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "MyMeth").WithArguments("NS.MyType.MyMeth", "0") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("MyType").Single() as NamedTypeSymbol; Assert.Equal(4, type1.GetMembers().Length); // constructor included } [Fact] public void CS0102ERR_DuplicateNameInClass05() { CreateCompilation( @"class C { void P() { } int P { get { return 0; } } object Q { get; set; } void Q(int x, int y) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 9), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 10)); } [Fact] public void CS0102ERR_DuplicateNameInClass06() { CreateCompilation( @"class C { private double get_P; // CS0102 private int set_P { get { return 0; } } // CS0102 void get_Q(object o) { } // no error class set_Q { } // CS0102 public int P { get; set; } object Q { get { return null; } } object R { set { } } enum get_R { } // CS0102 struct set_R { } // CS0102 }") .VerifyDiagnostics( // (7,20): error CS0102: The type 'C' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C", "get_P"), // (7,25): error CS0102: The type 'C' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_P"), // (8,12): error CS0102: The type 'C' already contains a definition for 'set_Q' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "set_Q"), // (9,12): error CS0102: The type 'C' already contains a definition for 'get_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "R").WithArguments("C", "get_R"), // (9,16): error CS0102: The type 'C' already contains a definition for 'set_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_R"), // (3,20): warning CS0169: The field 'C.get_P' is never used // private double get_P; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("C.get_P")); } [Fact] public void CS0102ERR_DuplicateNameInClass07() { CreateCompilation( @"class C { public int P { get { return 0; } set { } } public bool P { get { return false; } } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(8, 17)); } [WorkItem(538616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538616")] [Fact] public void CS0102ERR_DuplicateNameInClass08() { var text = @" class A<T> { void T() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 10 }); } [WorkItem(538917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538917")] [Fact] public void CS0102ERR_DuplicateNameInClass09() { var text = @" class A<T> { class T<S> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 11 }); } [WorkItem(538634, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538634")] [Fact] public void CS0102ERR_DuplicateNameInClass10() { var text = @"class C<A, B, D, E, F, G> { object A; void B() { } object D { get; set; } class E { } struct F { } enum G { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'A' // object A; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "A").WithArguments("C<A, B, D, E, F, G>", "A"), // (4,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'B' // void B() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "B").WithArguments("C<A, B, D, E, F, G>", "B"), // (5,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'D' // object D { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C<A, B, D, E, F, G>", "D"), // (6,11): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'E' // class E { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C<A, B, D, E, F, G>", "E"), // (7,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'F' // struct F { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C<A, B, D, E, F, G>", "F"), // (8,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'G' // enum G { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C<A, B, D, E, F, G>", "G"), // (3,12): warning CS0169: The field 'C<A, B, D, E, F, G>.A' is never used // object A; Diagnostic(ErrorCode.WRN_UnreferencedField, "A").WithArguments("C<A, B, D, E, F, G>.A")); } [Fact] public void CS0101ERR_DuplicateNameInNS05() { CreateCompilation( @"namespace N { enum E { A, B } enum E { A } // CS0101 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "E").WithArguments("E", "N").WithLocation(4, 10)); } [WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")] [Fact] public void CS0101ERR_DuplicateNameInNS06() { CreateCompilation( @"namespace N { interface I { int P { get; } object Q { get; } } interface I // CS0101 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0101 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0101 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0101: The namespace 'N' already contains a definition for 'I' // interface I // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "I").WithArguments("I", "N"), // (17,12): error CS0101: The namespace 'N' already contains a definition for 'S' // struct S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (22,11): error CS0101: The namespace 'N' already contains a definition for 'S' // class S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (27,18): error CS0101: The namespace 'N' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "D").WithArguments("D", "N"), // (24,16): warning CS0169: The field 'N.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("N.S.T"), // (20,13): warning CS0169: The field 'N.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("N.S.I") ); } [WorkItem(539742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539742")] [Fact] public void CS0102ERR_DuplicateNameInClass11() { CreateCompilation( @"class C { enum E { A, B } enum E { A } // CS0102 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "E").WithLocation(4, 10)); } [WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")] [Fact] public void CS0102ERR_DuplicateNameInClass12() { CreateCompilation( @"class C { interface I { int P { get; } object Q { get; } } interface I // CS0102 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0102 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0102 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0102: The type 'C' already contains a definition for 'I' // interface I // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("C", "I"), // (17,12): error CS0102: The type 'C' already contains a definition for 'S' // struct S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (22,11): error CS0102: The type 'C' already contains a definition for 'S' // class S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (27,18): error CS0102: The type 'C' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C", "D"), // (24,16): warning CS0169: The field 'C.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("C.S.T"), // (20,13): warning CS0169: The field 'C.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("C.S.I") ); } [Fact] public void CS0102ERR_DuplicateNameInClass13() { CreateCompilation( @"class C { private double add_E; // CS0102 private event System.Action remove_E; // CS0102 void add_F(object o) { } // no error class remove_F { } // CS0102 public event System.Action E; event System.Action F; event System.Action G; enum add_G { } // CS0102 struct remove_G { } // CS0102 }") .VerifyDiagnostics( // (72): error CS0102: The type 'C' already contains a definition for 'add_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "add_E"), // (72): error CS0102: The type 'C' already contains a definition for 'remove_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "remove_E"), // (8,25): error CS0102: The type 'C' already contains a definition for 'remove_F' // event System.Action F; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C", "remove_F"), // (9,25): error CS0102: The type 'C' already contains a definition for 'add_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "add_G"), // (9,25): error CS0102: The type 'C' already contains a definition for 'remove_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "remove_G"), // (8,25): warning CS0067: The event 'C.F' is never used // event System.Action F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("C.F"), // (3,20): warning CS0169: The field 'C.add_E' is never used // private double add_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "add_E").WithArguments("C.add_E"), // (4,33): warning CS0067: The event 'C.remove_E' is never used // private event System.Action remove_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "remove_E").WithArguments("C.remove_E"), // (72): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E"), // (9,25): warning CS0067: The event 'C.G' is never used // event System.Action G; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "G").WithArguments("C.G")); } [Fact] public void CS0102ERR_DuplicateNameInClass14() { var text = @"using System.Runtime.CompilerServices; interface I { object this[object index] { get; set; } void Item(); } struct S { [IndexerName(""P"")] object this[object index] { get { return null; } } object Item; // no error object P; } class A { object get_Item; object set_Item; object this[int x, int y] { set { } } } class B { [IndexerName(""P"")] object this[object index] { get { return null; } } object get_Item; // no error object get_P; } class A1 { internal object this[object index] { get { return null; } } } class A2 { internal object Item; // no error } class B1 : A1 { internal object Item; } class B2 : A2 { internal object this[object index] { get { return null; } } // no error }"; CreateCompilation(text).VerifyDiagnostics( // (4,12): error CS0102: The type 'I' already contains a definition for 'Item' // object this[object index] { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("I", "Item"), // (10,12): error CS0102: The type 'S' already contains a definition for 'P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("S", "P"), // (18,12): error CS0102: The type 'A' already contains a definition for 'get_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (18,33): error CS0102: The type 'A' already contains a definition for 'set_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (23,33): error CS0102: The type 'B' already contains a definition for 'get_P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("B", "get_P"), // (11,12): warning CS0169: The field 'S.Item' is never used // object Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("S.Item"), // (12,12): warning CS0169: The field 'S.P' is never used // object P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("S.P"), // (16,12): warning CS0169: The field 'A.get_Item' is never used // object get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item"), // (17,12): warning CS0169: The field 'A.set_Item' is never used // object set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item"), // (24,12): warning CS0169: The field 'B.get_Item' is never used // object get_Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("B.get_Item"), // (25,12): warning CS0169: The field 'B.get_P' is never used // object get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("B.get_P"), // (33,21): warning CS0649: Field 'A2.Item' is never assigned to, and will always have its default value null // internal object Item; // no error Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("A2.Item", "null"), // (37,21): warning CS0649: Field 'B1.Item' is never assigned to, and will always have its default value null // internal object Item; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("B1.Item", "null") ); } // Indexers without IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass15() { var template = @" class A {{ public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilation(string.Format(template, "int Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item"), // (5,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); // Error even though the indexer doesn't have a getter CreateCompilation(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (5,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilation(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (5,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); // Error even though the signatures don't match CreateCompilation(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item")); // Since the signatures don't match CreateCompilation(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } // Indexers with IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass16() { var template = @" using System.Runtime.CompilerServices; class A {{ [IndexerName(""P"")] public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilation(string.Format(template, "int P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P"), // (7,9): warning CS0169: The field 'A.P' is never used // int P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("A.P")); // Error even though the indexer doesn't have a getter CreateCompilation(string.Format(template, "int get_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_P"), // (7,9): warning CS0169: The field 'A.get_P' is never used // int get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("A.get_P")); CreateCompilation(string.Format(template, "int set_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_P"), // (7,9): warning CS0169: The field 'A.set_P' is never used // int set_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_P").WithArguments("A.set_P")); // Error even though the signatures don't match CreateCompilation(string.Format(template, "int P() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P")); // Since the signatures don't match CreateCompilation(string.Format(template, "int set_P() { return 0; }")).VerifyDiagnostics(); // No longer have issues with "Item" names CreateCompilation(string.Format(template, "int Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); CreateCompilation(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilation(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); CreateCompilation(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics(); CreateCompilation(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } [WorkItem(539625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539625")] [Fact] public void CS0104ERR_AmbigContext02() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I<string>.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I<A1> { public static int Method() { return 1; } } namespace LevelThree { public class I<A1> { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [Fact] public void CS0104ERR_AmbigContext03() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I { public static int Method() { return 1; } } namespace LevelThree { public class I { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [WorkItem(540255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540255")] [Fact] public void CS0122ERR_BadAccess01() { var text = @" interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Goo(new A.C()); } static void Goo<T>(I<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 15, Column = 9 }); } [Fact] public void CS0122ERR_BadAccess02() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Goo(new A.C()); } static void Goo<T>(I<T> x) { } static void Goo<T>(J<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); // no errors } [Fact] public void CS0122ERR_BadAccess03() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { System.Console.WriteLine(""I""); } // static void M<T>(J<T> c) // { // System.Console.WriteLine(""J""); // } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 29, Column = 15 }); } [Fact] public void CS0122ERR_BadAccess04() { var text = @"using System; interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void M<T>(J<T> c) { Console.WriteLine(""J""); } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(3202, "DevDiv_Projects/Roslyn")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_InaccessibleImport() { var text = @"using A = A; namespace X { using B; } static class A { private static class B { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,11): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // using B; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(4, 11), // (1,1): info CS8019: Unnecessary using directive. // using A = A; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = A;").WithLocation(1, 1), // (4,5): info CS8019: Unnecessary using directive. // using B; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using B;").WithLocation(4, 5)); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_1() { var text = @"class ClassA { object F = new { f1<int> = 1 }; public static int f1 { get { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,22): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. // object F = new { f1<int> = 1 }; Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "f1<int> = 1").WithLocation(3, 22), // (3,22): error CS0307: The property 'ClassA.f1' cannot be used with type arguments // object F = new { f1<int> = 1 }; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f1<int>").WithArguments("ClassA.f1", "property").WithLocation(3, 22)); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_2() { var text = @"class ClassA { object F = new { f1<T> }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_TypeArgsNotAllowed, Line = 3, Column = 22 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_3() { var text = @"class ClassA { object F = new { f1+ }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidExprTerm, Line = 3, Column = 26 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_4() { var text = @"class ClassA { object F = new { f1<int> }; public static int f1<T>() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,22): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. // object F = new { f1<int> }; Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "f1<int>").WithLocation(3, 22), // (3,22): error CS0828: Cannot assign method group to anonymous type property // object F = new { f1<int> }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "f1<int>").WithArguments("method group").WithLocation(3, 22)); } [Fact] public void CS7025ERR_BadVisEventType() { var text = @"internal interface InternalInterface { } internal delegate void InternalDelegate(); public class PublicClass { protected class Protected { } public event System.Action<InternalInterface> A; public event System.Action<InternalClass> B; internal event System.Action<Protected> C; public event InternalDelegate D; public event InternalDelegate E { add { } remove { } } } internal class InternalClass : PublicClass { public event System.Action<Protected> F; } "; CreateCompilation(text).VerifyDiagnostics( // (9,51): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalInterface>' is less accessible than event 'PublicClass.A' // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.ERR_BadVisEventType, "A").WithArguments("PublicClass.A", "System.Action<InternalInterface>"), // (10,47): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalClass>' is less accessible than event 'PublicClass.B' // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.ERR_BadVisEventType, "B").WithArguments("PublicClass.B", "System.Action<InternalClass>"), // (11,45): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'PublicClass.C' // internal event System.Action<Protected> C; Diagnostic(ErrorCode.ERR_BadVisEventType, "C").WithArguments("PublicClass.C", "System.Action<PublicClass.Protected>"), // (13,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.D' // public event InternalDelegate D; Diagnostic(ErrorCode.ERR_BadVisEventType, "D").WithArguments("PublicClass.D", "InternalDelegate"), // (14,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.E' // public event InternalDelegate E { add { } remove { } } Diagnostic(ErrorCode.ERR_BadVisEventType, "E").WithArguments("PublicClass.E", "InternalDelegate"), // (18,43): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'InternalClass.F' // public event System.Action<Protected> F; Diagnostic(ErrorCode.ERR_BadVisEventType, "F").WithArguments("InternalClass.F", "System.Action<PublicClass.Protected>"), // (9,51): warning CS0067: The event 'PublicClass.A' is never used // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "A").WithArguments("PublicClass.A"), // (10,47): warning CS0067: The event 'PublicClass.B' is never used // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("PublicClass.B"), // (11,45): warning CS0067: The event 'PublicClass.C' is never used // internal event System.Action<Protected> C; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "C").WithArguments("PublicClass.C"), // (13,35): warning CS0067: The event 'PublicClass.D' is never used // public event InternalDelegate D; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "D").WithArguments("PublicClass.D"), // (18,43): warning CS0067: The event 'InternalClass.F' is never used // public event System.Action<Protected> F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("InternalClass.F")); } [Fact, WorkItem(543386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543386")] public void VolatileFieldWithGenericTypeConstrainedToClass() { var text = @" public class C {} class G<T> where T : C { public volatile T Fld = default(T); } "; CreateCompilation(text).VerifyDiagnostics(); } #endregion [WorkItem(7920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7920")] [Fact()] public void Bug7920() { var comp1 = CreateCompilation(@" public class MyAttribute1 : System.Attribute {} ", options: TestOptions.ReleaseDll, assemblyName: "Bug7920_CS"); var comp2 = CreateCompilation(@" public class MyAttribute2 : MyAttribute1 {} ", new[] { new CSharpCompilationReference(comp1) }, options: TestOptions.ReleaseDll); var expected = new[] { // (2,2): error CS0012: The type 'MyAttribute1' is defined in an assembly that is not referenced. You must add a reference to assembly 'Bug7920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [MyAttribute2] Diagnostic(ErrorCode.ERR_NoTypeDef, "MyAttribute2").WithArguments("MyAttribute1", "Bug7920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") }; var source3 = @" [MyAttribute2] public class Test {} "; var comp3 = CreateCompilation(source3, new[] { new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseDll); comp3.GetDiagnostics().Verify(expected); var comp4 = CreateCompilation(source3, new[] { comp2.EmitToImageReference() }, options: TestOptions.ReleaseDll); comp4.GetDiagnostics().Verify(expected); } [Fact, WorkItem(345, "https://github.com/dotnet/roslyn")] public void InferredStaticTypeArgument() { var source = @"class Program { static void Main(string[] args) { M(default(C)); } public static void M<T>(T t) { } } static class C { }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS0718: 'C': static types cannot be used as type arguments // M(default(C)); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "M").WithArguments("C").WithLocation(5, 9) ); } [Fact, WorkItem(511, "https://github.com/dotnet/roslyn")] public void StaticTypeArgumentOfDynamicInvocation() { var source = @"static class S {} class C { static void M() { dynamic d1 = 123; d1.N<S>(); // The dev11 compiler does not diagnose this } static void Main() {} }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AbstractInScript() { var source = @"internal abstract void M(); internal abstract object P { get; } internal abstract event System.EventHandler E;"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (1,24): error CS0513: 'M()' is abstract but it is contained in non-abstract type 'Script' // internal abstract void M(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M").WithArguments("M()", "Script").WithLocation(1, 24), // (2,30): error CS0513: 'P.get' is abstract but it is contained in non-abstract type 'Script' // internal abstract object P { get; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("P.get", "Script").WithLocation(2, 30), // (3,45): error CS0513: 'E' is abstract but it is contained in non-abstract type 'Script' // internal abstract event System.EventHandler E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("E", "Script").WithLocation(3, 45)); } [WorkItem(529225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529225")] [Fact] public void AbstractInSubmission() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source = @"internal abstract void M(); internal abstract object P { get; } internal abstract event System.EventHandler E;"; var submission = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Script), new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }); submission.VerifyDiagnostics( // (1,24): error CS0513: 'M()' is abstract but it is contained in non-abstract type 'Script' // internal abstract void M(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M").WithArguments("M()", "Script").WithLocation(1, 24), // (2,30): error CS0513: 'P.get' is abstract but it is contained in non-abstract type 'Script' // internal abstract object P { get; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("P.get", "Script").WithLocation(2, 30), // (3,45): error CS0513: 'E' is abstract but it is contained in non-abstract type 'Script' // internal abstract event System.EventHandler E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("E", "Script").WithLocation(3, 45)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsOfATypeToDifferentAssembliesWithoutUsingItShouldNotReportAnError() { var forwardingIL = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly Forwarding { } .module Forwarding.dll .assembly extern Destination1 { } .assembly extern Destination2 { } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 } .class public auto ansi beforefieldinit TestSpace.ExistingReference extends [mscorlib]System.Object { .field public static literal string Value = ""TEST VALUE"" .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: nop IL_0007: ret } }"; var ilReference = CompileIL(forwardingIL, prependDefaultHeader: false); var code = @" using TestSpace; namespace UserSpace { public class Program { public static void Main() { System.Console.WriteLine(ExistingReference.Value); } } }"; CompileAndVerify( source: code, references: new MetadataReference[] { ilReference }, expectedOutput: "TEST VALUE"); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsOfFullyQualifiedTypeToDifferentAssembliesWhileReferencingItShouldErrorOut() { var userCode = @" namespace ForwardingNamespace { public class Program { public static void Main() { new Destination.TestClass(); } } }"; var forwardingIL = @" .assembly extern Destination1 { .ver 1:0:0:0 } .assembly extern Destination2 { .ver 1:0:0:0 } .assembly Forwarder { .ver 1:0:0:0 } .module ForwarderModule.dll .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 }"; var compilation = CreateCompilationWithILAndMscorlib40(userCode, forwardingIL, appendDefaultHeader: false); compilation.VerifyDiagnostics( // (8,29): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestClass").WithArguments("ForwarderModule.dll", "Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination.TestClass", "Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 29), // (8,29): error CS0234: The type or namespace name 'TestClass' does not exist in the namespace 'Destination' (are you missing an assembly reference?) // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestClass").WithArguments("TestClass", "Destination").WithLocation(8, 29)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsToManyAssembliesShouldJustReportTheFirstTwo() { var userCode = @" namespace ForwardingNamespace { public class Program { public static void Main() { new Destination.TestClass(); } } }"; var forwardingIL = @" .assembly Forwarder { } .module ForwarderModule.dll .assembly extern Destination1 { } .assembly extern Destination2 { } .assembly extern Destination3 { } .assembly extern Destination4 { } .assembly extern Destination5 { } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 } .class extern forwarder Destination.TestClass { .assembly extern Destination3 } .class extern forwarder Destination.TestClass { .assembly extern Destination4 } .class extern forwarder Destination.TestClass { .assembly extern Destination5 } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 }"; var compilation = CreateCompilationWithILAndMscorlib40(userCode, forwardingIL, appendDefaultHeader: false); compilation.VerifyDiagnostics( // (8,29): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestClass").WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination.TestClass", "Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 29), // (8,29): error CS0234: The type or namespace name 'TestClass' does not exist in the namespace 'Destination' (are you missing an assembly reference?) // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestClass").WithArguments("TestClass", "Destination").WithLocation(8, 29)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void RequiredExternalTypesForAMethodSignatureWillReportErrorsIfForwardedToMultipleAssemblies() { // The scenario is that assembly A is calling a method from assembly B. This method has a parameter of a type that lives // in assembly C. If A is compiled against B and C, it should compile successfully. // Now if assembly C is replaced with assembly C2, that forwards the type to both D1 and D2, it should fail with the appropriate error. var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static void MethodB(ClassC obj) { System.Console.WriteLine(obj.GetHashCode()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeA = @" using B; namespace A { public class ClassA { public void MethodA() { ClassB.MethodB(null); } } }"; CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC }, assemblyName: "A").VerifyDiagnostics(); // No Errors var codeC2 = @" .assembly C { } .module CModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder C.ClassC { .assembly extern D1 } .class extern forwarder C.ClassC { .assembly extern D2 }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2 }, assemblyName: "A").VerifyDiagnostics( // (10,13): error CS8329: Module 'CModule.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // ClassB.MethodB(null); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "ClassB.MethodB").WithArguments("CModule.dll", "C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C.ClassC", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10332")] [WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleTypeForwardersToTheSameAssemblyShouldNotResultInMultipleForwardError() { var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static string MethodB(ClassC obj) { return ""obj is "" + (obj == null ? ""null"" : obj.ToString()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeA = @" using B; namespace A { public class ClassA { public static void Main() { System.Console.WriteLine(ClassB.MethodB(null)); } } }"; CompileAndVerify( source: codeA, references: new MetadataReference[] { referenceB, referenceC }, expectedOutput: "obj is null"); var codeC2 = @" .assembly C { .ver 0:0:0:0 } .assembly extern D { } .class extern forwarder C.ClassC { .assembly extern D } .class extern forwarder C.ClassC { .assembly extern D }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2 }).VerifyDiagnostics( // (10,38): error CS0012: The type 'ClassC' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(ClassB.MethodB(null)); Diagnostic(ErrorCode.ERR_NoTypeDef, "ClassB.MethodB").WithArguments("C.ClassC", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(10, 38)); var codeD = @" namespace C { public class ClassC { } }"; var referenceD = CreateCompilation(codeD, assemblyName: "D").EmitToImageReference(); CompileAndVerify( source: codeA, references: new MetadataReference[] { referenceB, referenceC2, referenceD }, expectedOutput: "obj is null"); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void CompilingModuleWithMultipleForwardersToDifferentAssembliesShouldErrorOut() { var ilSource = @" .module ForwarderModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var ilModule = GetILModuleReference(ilSource, prependDefaultHeader: false); CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule }, assemblyName: "Forwarder").VerifyDiagnostics( // error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies).WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void CompilingModuleWithMultipleForwardersToTheSameAssemblyShouldNotProduceMultipleForwardingErrors() { var ilSource = @" .assembly extern D { } .class extern forwarder Testspace.TestType { .assembly extern D } .class extern forwarder Testspace.TestType { .assembly extern D }"; var ilModule = GetILModuleReference(ilSource, prependDefaultHeader: false); CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule }).VerifyDiagnostics( // error CS0012: The type 'TestType' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("Testspace.TestType", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); var dCode = @" namespace Testspace { public class TestType { } }"; var dReference = CreateCompilation(dCode, assemblyName: "D").EmitToImageReference(); // Now compilation succeeds CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule, dReference }).VerifyDiagnostics(); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void LookingUpATypeForwardedTwiceInASourceCompilationReferenceShouldFail() { // This test specifically tests that SourceAssembly symbols also produce this error (by using a CompilationReference instead of the usual PEAssembly symbol) var ilSource = @" .module ForwarderModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var ilModuleReference = GetILModuleReference(ilSource, prependDefaultHeader: false); var forwarderCompilation = CreateEmptyCompilation( source: string.Empty, references: new MetadataReference[] { ilModuleReference }, options: TestOptions.DebugDll, assemblyName: "Forwarder"); var csSource = @" namespace UserSpace { public class UserClass { public static void Main() { var obj = new Testspace.TestType(); } } }"; var userCompilation = CreateCompilation( source: csSource, references: new MetadataReference[] { forwarderCompilation.ToMetadataReference() }, assemblyName: "UserAssembly"); userCompilation.VerifyDiagnostics( // (8,37): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestType").WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 37), // (8,37): error CS0234: The type or namespace name 'TestType' does not exist in the namespace 'Testspace' (are you missing an assembly reference?) // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType").WithArguments("TestType", "Testspace").WithLocation(8, 37)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void ForwardingErrorsInLaterModulesAlwaysOverwriteOnesInEarlierModules() { var module1IL = @" .module module1IL.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var module1Reference = GetILModuleReference(module1IL, prependDefaultHeader: false); var module2IL = @" .module module12L.dll .assembly extern D3 { } .assembly extern D4 { } .class extern forwarder Testspace.TestType { .assembly extern D3 } .class extern forwarder Testspace.TestType { .assembly extern D4 }"; var module2Reference = GetILModuleReference(module2IL, prependDefaultHeader: false); var forwarderCompilation = CreateEmptyCompilation( source: string.Empty, references: new MetadataReference[] { module1Reference, module2Reference }, options: TestOptions.DebugDll, assemblyName: "Forwarder"); var csSource = @" namespace UserSpace { public class UserClass { public static void Main() { var obj = new Testspace.TestType(); } } }"; var userCompilation = CreateCompilation( source: csSource, references: new MetadataReference[] { forwarderCompilation.ToMetadataReference() }, assemblyName: "UserAssembly"); userCompilation.VerifyDiagnostics( // (8,37): error CS8329: Module 'module12L.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestType").WithArguments("module12L.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,37): error CS0234: The type or namespace name 'TestType' does not exist in the namespace 'Testspace' (are you missing an assembly reference?) // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType").WithArguments("TestType", "Testspace")); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsThatChainResultInTheSameAssemblyShouldStillProduceAnError() { // The scenario is that assembly A is calling a method from assembly B. This method has a parameter of a type that lives // in assembly C. Now if assembly C is replaced with assembly C2, that forwards the type to both D and E, and D forwards it to E, // it should fail with the appropriate error. var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static void MethodB(ClassC obj) { System.Console.WriteLine(obj.GetHashCode()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeC2 = @" .assembly C { } .module C.dll .assembly extern D { } .assembly extern E { } .class extern forwarder C.ClassC { .assembly extern D } .class extern forwarder C.ClassC { .assembly extern E }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); var codeD = @" .assembly D { } .assembly extern E { } .class extern forwarder C.ClassC { .assembly extern E }"; var referenceD = CompileIL(codeD, prependDefaultHeader: false); var referenceE = CreateCompilation(codeC, assemblyName: "E").EmitToImageReference(); var codeA = @" using B; using C; namespace A { public class ClassA { public void MethodA(ClassC obj) { ClassB.MethodB(obj); } } }"; CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2, referenceD, referenceE }, assemblyName: "A").VerifyDiagnostics( // (11,13): error CS8329: Module 'C.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // ClassB.MethodB(obj); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "ClassB.MethodB").WithArguments("C.dll", "C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C.ClassC", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 13)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithRef() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithIn() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(in int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithOut() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithNone() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithIn() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(in int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithOut() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithNone() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithRef() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithOut() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithNone() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithRef() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithIn() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(in int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void MethodWithNoReturnTypeShouldNotComplainAboutStaticCtor() { CreateCompilation(@" class X { private static Y(int i) {} }").VerifyDiagnostics( // (4,20): error CS1520: Method must have a return type // private static Y(int i) {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Y").WithLocation(4, 20)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; 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 partial class CompilationErrorTests : CompilingTestBase { #region Symbol Error Tests private static readonly ModuleMetadata s_mod1 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod01); private static readonly ModuleMetadata s_mod2 = ModuleMetadata.CreateFromImage(TestResources.DiagnosticTests.ErrTestMod02); [Fact()] public void CS0148ERR_BadDelegateConstructor() { var il = @" .class public auto ansi sealed F extends [mscorlib]System.MulticastDelegate { .method public hidebysig specialname rtspecialname instance void .ctor( //object 'object', native int 'method') runtime managed { } // end of method F::.ctor .method public hidebysig newslot virtual instance void Invoke() runtime managed { } // end of method F::Invoke .method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke(class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { } // end of method F::BeginInvoke .method public hidebysig newslot virtual instance void EndInvoke(class [mscorlib]System.IAsyncResult result) runtime managed { } // end of method F::EndInvoke } // end of class F "; var source = @" class C { void Goo() { F del = Goo; del(); //need to use del or the delegate receiver alone is emitted in optimized code. } } "; var comp = CreateCompilationWithILAndMscorlib40(source, il); var emitResult = comp.Emit(new System.IO.MemoryStream()); emitResult.Diagnostics.Verify(Diagnostic(ErrorCode.ERR_BadDelegateConstructor, "Goo").WithArguments("F")); } /// <summary> /// This error is specific to netmodule scenarios /// We used to give error CS0011: The base class or interface 'A' in assembly 'xxx' referenced by type 'B' could not be resolved /// In Roslyn we do not know the context in which the lookup was occurring, so we give a new, more generic message. /// </summary> [WorkItem(546451, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546451")] [Fact()] public void CS0011ERR_CantImportBase01() { var text1 = @"class A {}"; var text2 = @"class B : A {}"; var text = @" class Test { B b; void M() { Test x = b; } }"; var name1 = GetUniqueName(); var module1 = CreateCompilation(text1, options: TestOptions.ReleaseModule, assemblyName: name1); var module2 = CreateCompilation(text2, options: TestOptions.ReleaseModule, references: new[] { ModuleMetadata.CreateFromImage(module1.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); // use ref2 only var comp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new Dictionary<string, ReportDiagnostic>() { { MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_UnreferencedField), ReportDiagnostic.Suppress } }), references: new[] { ModuleMetadata.CreateFromImage(module2.EmitToArray(options: new EmitOptions(metadataOnly: true))).GetReference() }); comp.VerifyDiagnostics( // error CS8014: Reference to '1b2d660e-e892-4338-a4e7-f78ce7960ce9.netmodule' netmodule missing. Diagnostic(ErrorCode.ERR_MissingNetModuleReference).WithArguments(name1 + ".netmodule"), // (8,18): error CS7079: The type 'A' is defined in a module that has not been added. You must add the module '2bddf16b-09e6-4c4d-bd08-f348e194eca4.netmodule'. // Test x = b; Diagnostic(ErrorCode.ERR_NoTypeDefFromModule, "b").WithArguments("A", name1 + ".netmodule"), // (8,18): error CS0029: Cannot implicitly convert type 'B' to 'Test' // Test x = b; Diagnostic(ErrorCode.ERR_NoImplicitConv, "b").WithArguments("B", "Test"), // (4,7): warning CS0649: Field 'Test.b' is never assigned to, and will always have its default value null // B b; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "b").WithArguments("Test.b", "null") ); } [Fact] public void CS0012ERR_NoTypeDef01() { var text = @"namespace NS { class Test { TC5<string, string> var; // inherit C1 from MDTestLib1.dll void M() { Test x = var; } } }"; var ref2 = TestReferences.SymbolsTests.MDTestLib2; var comp = CreateCompilation(text, references: new MetadataReference[] { ref2 }, assemblyName: "Test3"); comp.VerifyDiagnostics( // (9,22): error CS0012: The type 'C1<>.C2<>' is defined in an assembly that is not referenced. You must add a reference to assembly 'MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // Test x = var; Diagnostic(ErrorCode.ERR_NoTypeDef, "var").WithArguments("C1<>.C2<>", "MDTestLib1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (9,22): error CS0029: Cannot implicitly convert type 'TC5<string, string>' to 'NS.Test' // Test x = var; Diagnostic(ErrorCode.ERR_NoImplicitConv, "var").WithArguments("TC5<string, string>", "NS.Test"), // (5,28): warning CS0649: Field 'NS.Test.var' is never assigned to, and will always have its default value null // TC5<string, string> var; // inherit C1 from MDTestLib1.dll Diagnostic(ErrorCode.WRN_UnassignedInternalField, "var").WithArguments("NS.Test.var", "null") ); } [Fact, WorkItem(8574, "DevDiv_Projects/Roslyn")] public void CS0029ERR_CannotImplicitlyConvertTypedReferenceToObject() { var text = @" class Program { static void M(System.TypedReference r) { var t = r.GetType(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,17): error CS0029: Cannot implicitly convert type 'System.TypedReference' to 'object' // var t = r.GetType(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "r").WithArguments("System.TypedReference", "object")); } // CS0036: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0050ERR_BadVisReturnType() { var text = @"class MyClass { } public class MyClass2 { public static MyClass MyMethod() // CS0050 { return new MyClass(); } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisReturnType, Line = 7, Column = 27 }); } [Fact] public void CS0051ERR_BadVisParamType01() { var text = @"public class A { class B { } public static void F(B b) // CS0051 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType02() { var text = @"class A { protected class P1 { } public class N { public void f(P1 p) { } protected void g(P1 p) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 7, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisParamType, Line = 8, Column = 24 }); } [Fact] public void CS0051ERR_BadVisParamType03() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 { public void M(B<A> arg) { } } public class C2 { public void M(B<object>.C<A> arg) { } } public class C3 { public void M(B<A>.C<object> arg) { } } public class C4 { public void M(B<B<A>>.C<object> arg) { } }"; CreateCompilation(source).VerifyDiagnostics( // (8,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>' is less accessible than method 'C1.M(B<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C1.M(B<A>)", "B<A>").WithLocation(8, 17), // (12,17): error CS0051: Inconsistent accessibility: parameter type 'B<object>.C<A>' is less accessible than method 'C2.M(B<object>.C<A>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C2.M(B<object>.C<A>)", "B<object>.C<A>").WithLocation(12, 17), // (16,17): error CS0051: Inconsistent accessibility: parameter type 'B<A>.C<object>' is less accessible than method 'C3.M(B<A>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C3.M(B<A>.C<object>)", "B<A>.C<object>").WithLocation(16, 17), // (20,17): error CS0051: Inconsistent accessibility: parameter type 'B<B<A>>.C<object>' is less accessible than method 'C4.M(B<B<A>>.C<object>)' Diagnostic(ErrorCode.ERR_BadVisParamType, "M").WithArguments("C4.M(B<B<A>>.C<object>)", "B<B<A>>.C<object>").WithLocation(20, 17)); } [Fact] public void CS0052ERR_BadVisFieldType() { var text = @"public class MyClass2 { public MyClass M; // CS0052 private class MyClass { } } public class MainClass { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisFieldType, Line = 3, Column = 20 }); } [Fact] public void CS0053ERR_BadVisPropertyType() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class B { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } protected class D { public PublicClass P { get; set; } public InternalInterface Q { get; set; } public ProtectedStruct R { get; set; } public PrivateClass S { get; set; } internal PublicClass T { get; set; } internal InternalInterface U { get; set; } internal ProtectedStruct V { get; set; } internal PrivateClass W { get; set; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.Q", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("A.R", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.S", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0053: Inconsistent accessibility: property return type 'A.ProtectedStruct' is less accessible than property 'A.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("A.V", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.W", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0053: Inconsistent accessibility: property return type 'InternalInterface' is less accessible than property 'A.B.Q' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "Q").WithArguments("A.B.Q", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("A.B.S", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0053: Inconsistent accessibility: property return type 'A.PrivateClass' is less accessible than property 'A.B.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("A.B.W", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.R' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "R").WithArguments("C.R", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.S", "C.PrivateClass").WithLocation(34, 25), // (370): error CS0053: Inconsistent accessibility: property return type 'C.ProtectedStruct' is less accessible than property 'C.V' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "V").WithArguments("C.V", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.W", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.S' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "S").WithArguments("C.D.S", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0053: Inconsistent accessibility: property return type 'C.PrivateClass' is less accessible than property 'C.D.W' Diagnostic(ErrorCode.ERR_BadVisPropertyType, "W").WithArguments("C.D.W", "C.PrivateClass").WithLocation(48, 31)); } [ClrOnlyFact] public void CS0054ERR_BadVisIndexerReturn() { var text = @"internal interface InternalInterface { } public class PublicClass { } public class A { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class B { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } } internal class C { protected struct ProtectedStruct { } private class PrivateClass { } public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } protected class D { public PublicClass this[int i] { get { return null; } } public InternalInterface this[object o] { get { return null; } } public ProtectedStruct this[string s] { set { } } public PrivateClass this[double d] { get { return null; } } internal PublicClass this[int x, int y] { get { return null; } } internal InternalInterface this[object x, object y] { get { return null; } } internal ProtectedStruct this[string x, string y] { set { } } internal PrivateClass this[double x, double y] { get { return null; } } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,30): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[object]", "InternalInterface").WithLocation(8, 30), // (9,28): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string]", "A.ProtectedStruct").WithLocation(9, 28), // (10,25): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double]", "A.PrivateClass").WithLocation(10, 25), // (13,30): error CS0054: Inconsistent accessibility: indexer return type 'A.ProtectedStruct' is less accessible than indexer 'A.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[string, string]", "A.ProtectedStruct").WithLocation(13, 30), // (14,27): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.this[double, double]", "A.PrivateClass").WithLocation(14, 27), // (18,34): error CS0054: Inconsistent accessibility: indexer return type 'InternalInterface' is less accessible than indexer 'A.B.this[object]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[object]", "InternalInterface").WithLocation(18, 34), // (20,29): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double]", "A.PrivateClass").WithLocation(20, 29), // (24,31): error CS0054: Inconsistent accessibility: indexer return type 'A.PrivateClass' is less accessible than indexer 'A.B.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("A.B.this[double, double]", "A.PrivateClass").WithLocation(24, 31), // (33,28): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string]", "C.ProtectedStruct").WithLocation(33, 28), // (34,24): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double]", "C.PrivateClass").WithLocation(34, 25), // (370): error CS0054: Inconsistent accessibility: indexer return type 'C.ProtectedStruct' is less accessible than indexer 'C.this[string, string]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[string, string]", "C.ProtectedStruct").WithLocation(37, 30), // (38,27): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.this[double, double]", "C.PrivateClass").WithLocation(38, 27), // (44,29): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double]", "C.PrivateClass").WithLocation(44, 29), // (48,31): error CS0054: Inconsistent accessibility: indexer return type 'C.PrivateClass' is less accessible than indexer 'C.D.this[double, double]' Diagnostic(ErrorCode.ERR_BadVisIndexerReturn, "this").WithArguments("C.D.this[double, double]", "C.PrivateClass").WithLocation(48, 31)); } [Fact] public void CS0055ERR_BadVisIndexerParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public int this[MyClass myClass] // CS0055 { get { return 0; } } } public class MyClass3 { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisIndexerParam, Line = 7, Column = 16 }); } [Fact] public void CS0056ERR_BadVisOpReturn() { var text = @"class MyClass { } public class A { public static implicit operator MyClass(A a) // CS0056 { return new MyClass(); } public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,28): error CS0056: Inconsistent accessibility: return type 'MyClass' is less accessible than operator 'A.implicit operator MyClass(A)' // public static implicit operator MyClass(A a) // CS0056 Diagnostic(ErrorCode.ERR_BadVisOpReturn, "MyClass").WithArguments("A.implicit operator MyClass(A)", "MyClass") ); } [Fact] public void CS0057ERR_BadVisOpParam() { var text = @"class MyClass //defaults to private accessibility { } public class MyClass2 { public static implicit operator MyClass2(MyClass iii) // CS0057 { return new MyClass2(); } public static void Main() { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (77): error CS0057: Inconsistent accessibility: parameter type 'MyClass' is less accessible than operator 'MyClass2.implicit operator MyClass2(MyClass)' // public static implicit operator MyClass2(MyClass iii) // CS0057 Diagnostic(ErrorCode.ERR_BadVisOpParam, "MyClass2").WithArguments("MyClass2.implicit operator MyClass2(MyClass)", "MyClass")); } [Fact] public void CS0058ERR_BadVisDelegateReturn() { var text = @"class MyClass { } public delegate MyClass MyClassDel(); // CS0058 public class A { public static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisDelegateReturn, Line = 5, Column = 25 }); } [WorkItem(542005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542005")] [Fact] public void CS0058ERR_BadVisDelegateReturn02() { var text = @" public class Outer { protected class Test { } public delegate Test MyDelegate(); }"; CreateCompilation(text).VerifyDiagnostics( // (5,26): error CS0058: Inconsistent accessibility: return type 'Outer.Test' is less accessible than delegate 'Outer.MyDelegate' // public delegate Test MyDelegate(); Diagnostic(ErrorCode.ERR_BadVisDelegateReturn, "MyDelegate").WithArguments("Outer.MyDelegate", "Outer.Test").WithLocation(5, 26) ); } [Fact] public void CS0059ERR_BadVisDelegateParam() { var text = @" class MyClass {} //defaults to internal accessibility public delegate void MyClassDel(MyClass myClass); // CS0059 "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,22): error CS0059: Inconsistent accessibility: parameter type 'MyClass' is less accessible than delegate 'MyClassDel' // public delegate void MyClassDel(MyClass myClass); // CS0059 Diagnostic(ErrorCode.ERR_BadVisDelegateParam, "MyClassDel").WithArguments("MyClassDel", "MyClass") ); } [Fact] public void CS0060ERR_BadVisBaseClass() { var text = @" namespace NS { internal class MyBase { } public class MyClass : MyBase { } public class Outer { private class MyBase { } protected class MyClass : MyBase { } protected class MyBase01 { } protected internal class MyClass01 : MyBase { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 11, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 34 }); } [WorkItem(539511, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539511")] [Fact] public void CS0060ERR_BadVisBaseClass02() { var text = @" public class A<T> { public class B<S> : A<B<D>.C> { public class C { } } protected class D { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 18 }); } [WorkItem(539512, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539512")] [Fact] public void CS0060ERR_BadVisBaseClass03() { var text = @" public class A { protected class B { protected class C { } } } internal class F : A { private class D : B { public class E : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 14, Column = 22 }); } [WorkItem(539546, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539546")] [Fact] public void CS0060ERR_BadVisBaseClass04() { var text = @" public class A<T> { private class B : A<B.C> { private class C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseClass, Line = 4, Column = 19 }); } [WorkItem(539562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539562")] [Fact] public void CS0060ERR_BadVisBaseClass05() { var text = @" class A<T> { class B : A<B> { public class C : B { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(539950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539950")] [Fact] public void CS0060ERR_BadVisBaseClass06() { var text = @" class A : C<E.F> { public class B { public class D { protected class F { } } } } class C<T> { } class E : A.B.D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // E.F is inaccessible where written; cascaded ERR_BadVisBaseClass is therefore suppressed new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 2, Column = 15 }); } [Fact] public void CS0060ERR_BadVisBaseClass07() { var source = @"internal class A { } public class B<T> { public class C<U> { } } public class C1 : B<A> { } public class C2 : B<object>.C<A> { } public class C3 : B<A>.C<object> { } public class C4 : B<B<A>>.C<object> { }"; CreateCompilation(source).VerifyDiagnostics( // (6,14): error CS0060: Inconsistent accessibility: base type 'B<A>' is less accessible than class 'C1' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C1").WithArguments("C1", "B<A>").WithLocation(6, 14), // (7,14): error CS0060: Inconsistent accessibility: base type 'B<object>.C<A>' is less accessible than class 'C2' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C2").WithArguments("C2", "B<object>.C<A>").WithLocation(7, 14), // (8,14): error CS0060: Inconsistent accessibility: base type 'B<A>.C<object>' is less accessible than class 'C3' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C3").WithArguments("C3", "B<A>.C<object>").WithLocation(8, 14), // (9,14): error CS0060: Inconsistent accessibility: base type 'B<B<A>>.C<object>' is less accessible than class 'C4' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C4").WithArguments("C4", "B<B<A>>.C<object>").WithLocation(9, 14)); } [Fact] public void CS0060ERR_BadVisBaseClass08() { var source = @"public class A { internal class B { public interface C { } } } public class B<T> : A { } public class C : B<A.B.C> { }"; CreateCompilation(source).VerifyDiagnostics( // (9,14): error CS0060: Inconsistent accessibility: base type 'B<A.B.C>' is less accessible than class 'C' Diagnostic(ErrorCode.ERR_BadVisBaseClass, "C").WithArguments("C", "B<A.B.C>").WithLocation(9, 14)); } [Fact] public void CS0061ERR_BadVisBaseInterface() { var text = @"internal interface A { } public interface AA : A { } // CS0061 // OK public interface B { } internal interface BB : B { } internal interface C { } internal interface CC : C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVisBaseInterface, Line = 2, Column = 18 }); } [Fact] public void CS0065ERR_EventNeedsBothAccessors() { var text = @"using System; public delegate void Eventhandler(object sender, int e); public class MyClass { public event EventHandler E1 { } // CS0065, public event EventHandler E2 { add { } } // CS0065, public event EventHandler E3 { remove { } } // CS0065, } "; CreateCompilation(text).VerifyDiagnostics( // (5,31): error CS0065: 'MyClass.E1': event property must have both add and remove accessors // public event EventHandler E1 { } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E1").WithArguments("MyClass.E1"), // (6,31): error CS0065: 'MyClass.E2': event property must have both add and remove accessors // public event EventHandler E2 { add { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E2").WithArguments("MyClass.E2"), // (71): error CS0065: 'MyClass.E3': event property must have both add and remove accessors // public event EventHandler E3 { remove { } } // CS0065, Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "E3").WithArguments("MyClass.E3")); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface01() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,22): error CS0065: 'i1.myevent': event property must have both add and remove accessors Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "myevent").WithArguments("i1.myevent")); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface02() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add; remove; } } "; CreateCompilation(text, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (6,35): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 35), // (6,43): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 43)); CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (6,35): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 35), // (6,43): error CS0073: An add or remove accessor must have a body // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_AddRemoveMustHaveBody, ";").WithLocation(6, 43), // (6,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(6, 32), // (6,37): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add; remove; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(6, 37) ); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface03() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} remove {} } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (5,39): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} remove {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "remove").WithArguments("default interface implementation", "8.0").WithLocation(5, 39) ); } [WorkItem(542570, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542570")] [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface04() { var text = @" delegate void myDelegate(int name = 1); interface i1 { event myDelegate myevent { add {} } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (5,32): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // event myDelegate myevent { add {} } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "add").WithArguments("default interface implementation", "8.0").WithLocation(5, 32), // (5,22): error CS0065: 'i1.myevent': event property must have both add and remove accessors // event myDelegate myevent { add {} } Diagnostic(ErrorCode.ERR_EventNeedsBothAccessors, "myevent").WithArguments("i1.myevent").WithLocation(5, 22) ); } [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface05() { var text = @" public interface I2 { } public interface I1 { event System.Action I2.P10; } "; CreateCompilation(text).VerifyDiagnostics( // (6,28): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P10").WithLocation(6, 28), // (6,25): error CS0540: 'I1.P10': containing type does not implement interface 'I2' // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P10", "I2").WithLocation(6, 25), // (6,28): error CS0539: 'I1.P10' in explicit interface declaration is not found among members of the interface that can be implemented // event System.Action I2.P10; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P10").WithArguments("I1.P10").WithLocation(6, 28) ); } [Fact] public void CS0065ERR_EventNeedsBothAccessors_Interface06() { var text = @" public interface I2 { } public interface I1 { event System.Action I2. P10; } "; CreateCompilation(text).VerifyDiagnostics( // (6,25): error CS0540: 'I1.P10': containing type does not implement interface 'I2' // event System.Action I2. Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I2").WithArguments("I1.P10", "I2").WithLocation(6, 25), // (7,1): error CS0071: An explicit interface implementation of an event must use event accessor syntax // P10; Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "P10").WithLocation(7, 1), // (7,1): error CS0539: 'I1.P10' in explicit interface declaration is not found among members of the interface that can be implemented // P10; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "P10").WithArguments("I1.P10").WithLocation(7, 1) ); } [Fact] public void CS0066ERR_EventNotDelegate() { var text = @" public class C { public event C Click; // CS0066 } "; CreateCompilation(text).VerifyDiagnostics( // (4,20): error CS0066: 'C.Click': event must be of a delegate type // public event C Click; // CS0066 Diagnostic(ErrorCode.ERR_EventNotDelegate, "Click").WithArguments("C.Click"), // (4,20): warning CS0067: The event 'C.Click' is never used // public event C Click; // CS0066 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Click").WithArguments("C.Click")); } [Fact] public void CS0068ERR_InterfaceEventInitializer() { var text = @" delegate void MyDelegate(); interface I { event MyDelegate d = new MyDelegate(M.f); // CS0068 } class M { event MyDelegate d = new MyDelegate(M.f); public static void f() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,22): error CS0068: 'I.d': event in interface cannot have initializer // event MyDelegate d = new MyDelegate(M.f); // CS0068 Diagnostic(ErrorCode.ERR_InterfaceEventInitializer, "d").WithArguments("I.d").WithLocation(6, 22), // (6,22): warning CS0067: The event 'I.d' is never used // event MyDelegate d = new MyDelegate(M.f); // CS0068 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "d").WithArguments("I.d").WithLocation(6, 22)); } [Fact] public void CS0072ERR_CantOverrideNonEvent() { var text = @"delegate void MyDelegate(); class Test1 { public virtual event MyDelegate MyEvent; public virtual void VMeth() { } } class Test2 : Test1 { public override event MyDelegate VMeth // CS0072 { add { VMeth += value; } remove { VMeth -= value; } } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (13,38): error CS0072: 'Test2.VMeth': cannot override; 'Test1.VMeth()' is not an event // public override event MyDelegate VMeth // CS0072 Diagnostic(ErrorCode.ERR_CantOverrideNonEvent, "VMeth").WithArguments("Test2.VMeth", "Test1.VMeth()"), // (5,37): warning CS0067: The event 'Test1.MyEvent' is never used // public virtual event MyDelegate MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("Test1.MyEvent")); } [Fact] public void CS0074ERR_AbstractEventInitializer() { var text = @" delegate void D(); abstract class Test { public abstract event D e = null; // CS0074 } "; CreateCompilation(text).VerifyDiagnostics( // (6,29): error CS0074: 'Test.e': abstract event cannot have initializer // public abstract event D e = null; // CS0074 Diagnostic(ErrorCode.ERR_AbstractEventInitializer, "e").WithArguments("Test.e").WithLocation(6, 29), // (6,29): warning CS0414: The field 'Test.e' is assigned but its value is never used // public abstract event D e = null; // CS0074 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "e").WithArguments("Test.e").WithLocation(6, 29)); } [Fact] public void CS0076ERR_ReservedEnumerator() { var text = @"enum E { value__ } enum F { A, B, value__ } enum G { X = 0, value__ = 1, Z = value__ + 1 } enum H { Value__ } // no error class C { E value__; // no error static void M() { F value__; // no error } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (1,10): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum E { value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (2,16): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum F { A, B, value__ } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (3,17): error CS0076: The enumerator name 'value__' is reserved and cannot be used // enum G { X = 0, value__ = 1, Z = value__ + 1 } Diagnostic(ErrorCode.ERR_ReservedEnumerator, "value__").WithArguments("value__"), // (10,11): warning CS0168: The variable 'value__' is declared but never used // F value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedVar, "value__").WithArguments("value__"), // (7,7): warning CS0169: The field 'C.value__' is never used // E value__; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "value__").WithArguments("C.value__") ); } /// <summary> /// Currently parser error 1001, 1003. Is that good enough? /// </summary> [Fact()] public void CS0081ERR_TypeParamMustBeIdentifier01() { var text = @"namespace NS { class C { int F<int>() { } // CS0081 } }"; // Triage decision was made to have this be a parse error as the grammar specifies it as such. // TODO: vsadov, the error recovery would be much nicer here if we consumed "int", bu tneed to consider other cases. CreateCompilationWithMscorlib46(text, parseOptions: TestOptions.Regular).VerifyDiagnostics( // (5,11): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '>' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(">", "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '(' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("(", "int").WithLocation(5, 11), // (5,14): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(5, 14), // (5,14): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, ">").WithArguments(",", ">").WithLocation(5, 14), // (5,15): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "(").WithLocation(5, 15), // (5,16): error CS8124: Tuple must contain at least two elements. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 16), // (5,18): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 18), // (5,18): error CS1026: ) expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(5, 18), // (5,15): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 15), // (5,9): error CS0161: 'C.F<>(int, (?, ?))': not all code paths return a value // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("NS.C.F<>(int, (?, ?))").WithLocation(5, 9) ); } /// <summary> /// Currently parser error 1001, 1003. Is that good enough? /// </summary> [Fact()] public void CS0081ERR_TypeParamMustBeIdentifier01WithCSharp6() { var text = @"namespace NS { class C { int F<int>() { } // CS0081 } }"; // Triage decision was made to have this be a parse error as the grammar specifies it as such. CreateCompilationWithMscorlib46(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6)).VerifyDiagnostics( // (5,11): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '>' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments(">", "int").WithLocation(5, 11), // (5,11): error CS1003: Syntax error, '(' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "int").WithArguments("(", "int").WithLocation(5, 11), // (5,14): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(5, 14), // (5,14): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, ">").WithArguments(",", ">").WithLocation(5, 14), // (5,15): error CS1003: Syntax error, ',' expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_SyntaxError, "(").WithArguments(",", "(").WithLocation(5, 15), // (5,15): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "()").WithArguments("tuples", "7.0").WithLocation(5, 15), // (5,16): error CS8124: Tuple must contain at least two elements. // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_TupleTooFewElements, ")").WithLocation(5, 16), // (5,18): error CS1001: Identifier expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_IdentifierExpected, "{").WithLocation(5, 18), // (5,18): error CS1026: ) expected // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_CloseParenExpected, "{").WithLocation(5, 18), // (5,15): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "()").WithArguments("System.ValueTuple`2").WithLocation(5, 15), // (5,9): error CS0161: 'C.F<>(int, (?, ?))': not all code paths return a value // int F<int>() { } // CS0081 Diagnostic(ErrorCode.ERR_ReturnExpected, "F").WithArguments("NS.C.F<>(int, (?, ?))").WithLocation(5, 9) ); } [Fact] public void CS0082ERR_MemberReserved01() { CreateCompilation( @"class C { public void set_P(int i) { } public int P { get; set; } public int get_P() { return 0; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(4, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(4, 25)); } [Fact] public void CS0082ERR_MemberReserved02() { CreateCompilation( @"class A { public void set_P(int i) { } } partial class B : A { public int P { get { return 0; } set { } } } partial class B { partial void get_P(); public void set_P() { } } partial class B { partial void get_P() { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "B").WithLocation(9, 9)); } [Fact] public void CS0082ERR_MemberReserved03() { CreateCompilation( @"abstract class C { public abstract object P { get; } protected abstract object Q { set; } internal object R { get; set; } protected internal object S { get { return null; } } private object T { set { } } object U { get { return null; } set { } } object get_P() { return null; } void set_P(object value) { } private object get_Q() { return null; } private void set_Q(object value) { } protected internal object get_R() { return null; } protected internal void set_R(object value) { } internal object get_S() { return null; } internal void set_S(object value) { } protected object get_T() { return null; } protected void set_T(object value) { } public object get_U() { return null; } public void set_U(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C").WithLocation(3, 32), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C").WithLocation(3, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "Q").WithArguments("get_Q", "C").WithLocation(4, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_R", "C").WithLocation(5, 25), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(5, 30), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_S", "C").WithLocation(6, 35), Diagnostic(ErrorCode.ERR_MemberReserved, "S").WithArguments("set_S", "C").WithLocation(6, 31), Diagnostic(ErrorCode.ERR_MemberReserved, "T").WithArguments("get_T", "C").WithLocation(7, 20), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_T", "C").WithLocation(7, 24), Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_U", "C").WithLocation(8, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_U", "C").WithLocation(8, 37)); } [Fact] public void CS0082ERR_MemberReserved04() { CreateCompilationWithMscorlib40AndSystemCore( @"class A<T, U> { public T P { get; set; } // CS0082 public U Q { get; set; } // no error public U R { get; set; } // no error public void set_P(T t) { } public void set_Q(object o) { } public void set_R(T t) { } } class B : A<object, object> { } class C { public dynamic P { get; set; } // CS0082 public dynamic Q { get; set; } // CS0082 public object R { get; set; } // CS0082 public object S { get; set; } // CS0082 public void set_P(object o) { } public void set_Q(dynamic o) { } public void set_R(object o) { } public void set_S(dynamic o) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "A<T, U>").WithLocation(3, 23), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_P", "C").WithLocation(15, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(16, 29), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_R", "C").WithLocation(17, 28), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(18, 28)); } [Fact] public void CS0082ERR_MemberReserved05() { CreateCompilation( @"class C { object P { get; set; } object Q { get; set; } object R { get; set; } object[] S { get; set; } public object get_P(object o) { return null; } // CS0082 public void set_P() { } public void set_P(ref object o) { } public void get_Q() { } // CS0082 public object set_Q(object o) { return null; } // CS0082 public object set_Q(out object o) { o = null; return null; } void set_S(params object[] args) { } // CS0082 } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_Q", "C").WithLocation(4, 16), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_Q", "C").WithLocation(4, 21), Diagnostic(ErrorCode.ERR_MemberReserved, "set").WithArguments("set_S", "C").WithLocation(6, 23)); } [Fact] public void CS0082ERR_MemberReserved06() { // No errors for explicit interface implementation. CreateCompilation( @"interface I { int get_P(); void set_P(int o); } class C : I { public int P { get; set; } int I.get_P() { return 0; } void I.set_P(int o) { } } ") .VerifyDiagnostics(); } [WorkItem(539770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539770")] [Fact] public void CS0082ERR_MemberReserved07() { // No errors for explicit interface implementation. CreateCompilation( @"class C { public object P { get { return null; } } object get_P() { return null; } void set_P(object value) { } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_MemberReserved, "get").WithArguments("get_P", "C"), Diagnostic(ErrorCode.ERR_MemberReserved, "P").WithArguments("set_P", "C")); } [Fact] public void CS0082ERR_MemberReserved08() { CreateCompilation( @"class C { public event System.Action E; void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,32): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("add_E", "C"), // (3,32): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E; Diagnostic(ErrorCode.ERR_MemberReserved, "E").WithArguments("remove_E", "C"), // (3,32): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0082ERR_MemberReserved09() { CreateCompilation( @"class C { public event System.Action E { add { } remove { } } void add_E(System.Action value) { } void remove_E(System.Action value) { } } ") .VerifyDiagnostics( // (3,36): error CS0082: Type 'C' already reserves a member called 'add_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "add").WithArguments("add_E", "C"), // (3,44): error CS0082: Type 'C' already reserves a member called 'remove_E' with the same parameter types // public event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_MemberReserved, "remove").WithArguments("remove_E", "C")); } [Fact] public void CS0100ERR_DuplicateParamName01() { var text = @"namespace NS { interface IGoo { void M1(byte b, sbyte b); } struct S { public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (5,31): error CS0100: The parameter name 'b' is a duplicate // void M1(byte b, sbyte b); Diagnostic(ErrorCode.ERR_DuplicateParamName, "b").WithArguments("b").WithLocation(5, 31), // (10,45): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 45), // (10,59): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 59), // (10,77): error CS0100: The parameter name 'p' is a duplicate // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(10, 77), // (10,82): error CS0229: Ambiguity between 'object' and 'ref string' // public void M2(object p, ref string p, ref string p, params ulong[] p) { p = null; } Diagnostic(ErrorCode.ERR_AmbigMember, "p").WithArguments("object", "ref string").WithLocation(10, 82) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS01() { var text = @"namespace NS { struct Test { } class Test { } interface Test { } namespace NS1 { interface A<T, V> { } class A<T, V> { } class A<T, V> { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 5, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 10, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 11, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0101ERR_DuplicateNameInNS02() { var text = @"namespace NS { interface IGoo<T, V> { } class IGoo<T, V> { } struct SS { } public class SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS03() { var text = @"namespace NS { interface IGoo<T, V> { } interface IGoo<T, V> { } struct SS { } public struct SS { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 4, Column = 15 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInNS, Line = 7, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0101ERR_DuplicateNameInNS04() { var text = @"namespace NS { partial class Goo<T, V> { } // no error, because ""partial"" partial class Goo<T, V> { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0102ERR_DuplicateNameInClass01() { var text = @"class A { int n = 0; long n = 1; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,10): error CS0102: The type 'A' already contains a definition for 'n' // long n = 1; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "n").WithArguments("A", "n"), // (3,9): warning CS0414: The field 'A.n' is assigned but its value is never used // int n = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n"), // (4,10): warning CS0414: The field 'A.n' is assigned but its value is never used // long n = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "n").WithArguments("A.n") ); var classA = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; var ns = classA.GetMembers("n"); Assert.Equal(2, ns.Length); foreach (var n in ns) { Assert.Equal(TypeKind.Struct, (n as FieldSymbol).Type.TypeKind); } } [Fact] public void CS0102ERR_DuplicateNameInClass02() { CreateCompilation( @"namespace NS { class C { interface I<T, U> { } interface I<T, U> { } struct S { } public struct S { } } struct S<X> { X x; C x; } } ") .VerifyDiagnostics( // (6,19): error CS0102: The type 'NS.C' already contains a definition for 'I' // interface I<T, U> { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I"), // (9,23): error CS0102: The type 'NS.C' already contains a definition for 'S' // public struct S { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S"), // (14,11): error CS0102: The type 'NS.S<X>' already contains a definition for 'x' // C x; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "x").WithArguments("NS.S<X>", "x"), // (13,11): warning CS0169: The field 'NS.S<X>.x' is never used // X x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x"), // (14,11): warning CS0169: The field 'NS.S<X>.x' is never used // C x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("NS.S<X>.x") ); // Dev10 miss this with previous errors } [Fact] public void CS0102ERR_DuplicateNameInClass03() { CreateCompilation( @"namespace NS { class C { interface I<T> { } class I<U> { } struct S { } class S { } enum E { } interface E { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("NS.C", "I").WithLocation(6, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("NS.C", "S").WithLocation(8, 15), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("NS.C", "E").WithLocation(10, 19)); } [Fact] public void CS0104ERR_AmbigContext01() { var text = @"namespace n1 { public interface IGoo<T> { } class A { } } namespace n3 { using n1; using n2; namespace n2 { public interface IGoo<V> { } public class A { } } public class C<X> : IGoo<X> { } struct S { A a; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,9): error CS0104: 'A' is an ambiguous reference between 'n1.A' and 'n3.n2.A' // A a; Diagnostic(ErrorCode.ERR_AmbigContext, "A").WithArguments("A", "n1.A", "n3.n2.A").WithLocation(22, 9), // (16,25): error CS0104: 'IGoo<>' is an ambiguous reference between 'n1.IGoo<T>' and 'n3.n2.IGoo<V>' // public class C<X> : IGoo<X> Diagnostic(ErrorCode.ERR_AmbigContext, "IGoo<X>").WithArguments("IGoo<>", "n1.IGoo<T>", "n3.n2.IGoo<V>").WithLocation(16, 25), // (22,11): warning CS0169: The field 'S.a' is never used // A a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("n3.S.a").WithLocation(22, 11) ); var ns3 = comp.SourceModule.GlobalNamespace.GetMember<NamespaceSymbol>("n3"); var classC = ns3.GetMember<NamedTypeSymbol>("C"); var classCInterface = classC.Interfaces().Single(); Assert.Equal("IGoo", classCInterface.Name); Assert.Equal(TypeKind.Error, classCInterface.TypeKind); var structS = ns3.GetMember<NamedTypeSymbol>("S"); var structSField = structS.GetMember<FieldSymbol>("a"); Assert.Equal("A", structSField.Type.Name); Assert.Equal(TypeKind.Error, structSField.Type.TypeKind); } [Fact] public void CS0106ERR_BadMemberFlag01() { var text = @"namespace MyNamespace { interface I { void m(); static public void f(); } public class MyClass { virtual ushort field; public void I.m() // CS0106 { } } }"; CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (11,24): error CS0106: The modifier 'virtual' is not valid for this item // virtual ushort field; Diagnostic(ErrorCode.ERR_BadMemberFlag, "field").WithArguments("virtual").WithLocation(11, 24), // (12,23): error CS0106: The modifier 'public' is not valid for this item // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_BadMemberFlag, "m").WithArguments("public").WithLocation(12, 23), // (12,21): error CS0540: 'MyClass.I.m()': containing type does not implement interface 'I' // public void I.m() // CS0106 Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I").WithArguments("MyNamespace.MyClass.MyNamespace.I.m()", "MyNamespace.I").WithLocation(12, 21), // (11,24): warning CS0169: The field 'MyClass.field' is never used // virtual ushort field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("MyNamespace.MyClass.field").WithLocation(11, 24), // (6,28): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "f").WithArguments("static", "7.0", "8.0").WithLocation(6, 28), // (6,28): error CS8503: The modifier 'public' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "f").WithArguments("public", "7.0", "8.0").WithLocation(6, 28), // (6,28): error CS0501: 'I.f()' must declare a body because it is not marked abstract, extern, or partial // static public void f(); // CS0106 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "f").WithArguments("MyNamespace.I.f()").WithLocation(6, 28) ); } [Fact] public void CS0106ERR_BadMemberFlag02() { var text = @"interface I { public static int P1 { get; } abstract int P2 { static set; } int P4 { new abstract get; } int P5 { static set; } int P6 { sealed get; } } class C { public int P1 { virtual get { return 0; } } internal int P2 { static set { } } static int P3 { new get { return 0; } } int P4 { sealed get { return 0; } } protected internal object P5 { get { return null; } extern set; } public extern object P6 { get; } // no error } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (3,23): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // public static int P1 { get; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("static", "7.0", "8.0").WithLocation(3, 23), // (3,23): error CS8503: The modifier 'public' is not valid for this item in C# 7. Please use language version '8.0' or greater. // public static int P1 { get; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P1").WithArguments("public", "7.0", "8.0").WithLocation(3, 23), // (4,18): error CS8503: The modifier 'abstract' is not valid for this item in C# 7. Please use language version '8.0' or greater. // abstract int P2 { static set; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P2").WithArguments("abstract", "7.0", "8.0").WithLocation(4, 18), // (4,30): error CS0106: The modifier 'static' is not valid for this item // abstract int P2 { static set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(4, 30), // (5,27): error CS0106: The modifier 'abstract' is not valid for this item // int P4 { new abstract get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("abstract").WithLocation(5, 27), // (5,27): error CS0106: The modifier 'new' is not valid for this item // int P4 { new abstract get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("new").WithLocation(5, 27), // (6,21): error CS0106: The modifier 'static' is not valid for this item // int P5 { static set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(6, 21), // (7,21): error CS0106: The modifier 'sealed' is not valid for this item // int P6 { sealed get; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("sealed").WithLocation(7, 21), // (11,29): error CS0106: The modifier 'virtual' is not valid for this item // public int P1 { virtual get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("virtual").WithLocation(11, 29), // (12,30): error CS0106: The modifier 'static' is not valid for this item // internal int P2 { static set { } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("static").WithLocation(12, 30), // (13,25): error CS0106: The modifier 'new' is not valid for this item // static int P3 { new get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("new").WithLocation(13, 25), // (14,21): error CS0106: The modifier 'sealed' is not valid for this item // int P4 { sealed get { return 0; } } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("sealed").WithLocation(14, 21), // (15,64): error CS0106: The modifier 'extern' is not valid for this item // protected internal object P5 { get { return null; } extern set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("extern").WithLocation(15, 64), // (16,31): warning CS0626: Method, operator, or accessor 'C.P6.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // public extern object P6 { get; } // no error Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.P6.get").WithLocation(16, 31) ); } [WorkItem(539584, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539584")] [Fact] public void CS0106ERR_BadMemberFlag03() { var text = @" class C { sealed private C() { } new abstract C(object o); public virtual C(C c) { } protected internal override C(int i, int j) { } volatile const int x = 1; } "; CreateCompilation(text).VerifyDiagnostics( // (4,20): error CS0106: The modifier 'sealed' is not valid for this item // sealed private C() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("sealed"), // (5,18): error CS0106: The modifier 'abstract' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,18): error CS0106: The modifier 'new' is not valid for this item // new abstract C(object o); Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("new"), // (6,20): error CS0106: The modifier 'virtual' is not valid for this item // public virtual C(C c) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("virtual"), // (73): error CS0106: The modifier 'override' is not valid for this item // protected internal override C(int i, int j) { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("override"), // (8,24): error CS0106: The modifier 'volatile' is not valid for this item // volatile const int x = 1; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile") ); } [Fact] public void CS0106ERR_BadMemberFlag04() { var text = @" class C { static int this[int x] { set { } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 4, Column = 16 }); } [Fact] public void CS0106ERR_BadMemberFlag05() { var text = @" struct Goo { public abstract void Bar1(); public virtual void Bar2() { } public virtual int Bar3 { get;set; } public abstract int Bar4 { get;set; } public abstract event System.EventHandler Bar5; public virtual event System.EventHandler Bar6; // prevent warning for test void OnBar() { Bar6?.Invoke(null, null); } public virtual int this[int x] { get { return 1;} set {;} } // use long for to prevent signature clash public abstract int this[long x] { get; set; } public sealed override string ToString() => null; } "; CreateCompilation(text).VerifyDiagnostics( // (6,24): error CS0106: The modifier 'virtual' is not valid for this item // public virtual int Bar3 { get;set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar3").WithArguments("virtual").WithLocation(6, 24), // (7,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int Bar4 { get;set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar4").WithArguments("abstract").WithLocation(7, 25), // (12,24): error CS0106: The modifier 'virtual' is not valid for this item // public virtual int this[int x] { get { return 1;} set {;} } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("virtual").WithLocation(12, 24), // (14,25): error CS0106: The modifier 'abstract' is not valid for this item // public abstract int this[long x] { get; set; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "this").WithArguments("abstract").WithLocation(14, 25), // (5,25): error CS0106: The modifier 'virtual' is not valid for this item // public virtual void Bar2() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar2").WithArguments("virtual").WithLocation(5, 25), // (4,26): error CS0106: The modifier 'abstract' is not valid for this item // public abstract void Bar1(); Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar1").WithArguments("abstract").WithLocation(4, 26), // (8,47): error CS0106: The modifier 'abstract' is not valid for this item // public abstract event System.EventHandler Bar5; Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar5").WithArguments("abstract").WithLocation(8, 47), // (9,46): error CS0106: The modifier 'virtual' is not valid for this item // public virtual event System.EventHandler Bar6; Diagnostic(ErrorCode.ERR_BadMemberFlag, "Bar6").WithArguments("virtual").WithLocation(9, 46), // (15,35): error CS0106: The modifier 'sealed' is not valid for this item // public sealed override string ToString() => null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "ToString").WithArguments("sealed").WithLocation(15, 35)); } [Fact] public void CS0106ERR_BadMemberFlag06() { var text = @"interface I { int P1 { get; } int P2 { get; set; } } class C : I { private int I.P1 { get { return 0; } } int I.P2 { private get { return 0; } set {} } } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0106: The modifier 'private' is not valid for this item // private int I.P1 Diagnostic(ErrorCode.ERR_BadMemberFlag, "P1").WithArguments("private").WithLocation(8, 19), // (15,17): error CS0106: The modifier 'private' is not valid for this item // private get { return 0; } Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("private").WithLocation(15, 17) ); } [Fact] public void CS0111ERR_MemberAlreadyExists01() { var text = @"class A { void Test() { } public static void Test() { } // CS0111 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MemberAlreadyExists, Line = 4, Column = 24 }); } [Fact] public void CS0111ERR_MemberAlreadyExists02() { var compilation = CreateCompilation( @"static class S { internal static void E<T>(this T t, object o) where T : new() { } internal static void E<T>(this T t, object o) where T : class { } internal static void E<U>(this U u, object o) { } }"); compilation.VerifyDiagnostics( // (4,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(4, 26), // (5,26): error CS0111: Type 'S' already defines a member called 'E' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "E").WithArguments("E", "S").WithLocation(5, 26)); } [Fact] public void CS0111ERR_MemberAlreadyExists03() { var compilation = CreateCompilation( @"class C { object this[object o] { get { return null; } set { } } object this[int x] { get { return null; } } int this[int y] { set { } } object this[object o] { get { return null; } set { } } } interface I { object this[int x, int y] { get; set; } I this[int a, int b] { get; } I this[int a, int b] { set; } I this[object a, object b] { get; } }"); compilation.VerifyDiagnostics( // (5,9): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(5, 9), // (6,12): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C").WithLocation(6, 12), // (11,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(11, 7), // (12,7): error CS0111: Type 'I' already defines a member called 'this' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "I").WithLocation(12, 7)); } [Fact] public void CS0111ERR_MemberAlreadyExists04() { var compilation = CreateCompilation( @" using AliasForI = I; public interface I { int this[int x] { get; set; } } public interface J { int this[int x] { get; set; } } public class C : I, J { int I.this[int x] { get { return 0; } set { } } int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 int J.this[int x] { get { return 0; } set { } } //fine public int this[int x] { get { return 0; } set { } } //fine } "); compilation.VerifyDiagnostics( // (13,14): error CS8646: 'I.this[int]' is explicitly implemented more than once. // public class C : I, J Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C").WithArguments("I.this[int]").WithLocation(13, 14), // (16,19): error CS0111: Type 'C' already defines a member called 'this' with the same parameter types // int AliasForI.this[int x] { get { return 0; } set { } } //CS0111 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "this").WithArguments("this", "C")); } /// <summary> /// Method signature comparison should ignore constraints. /// </summary> [Fact] public void CS0111ERR_MemberAlreadyExists05() { var compilation = CreateCompilation( @"class C { void M<T>(T t) where T : new() { } void M<U>(U u) where U : struct { } void M<T>(T t) where T : C { } } interface I<T> { void M<U>(); void M<U>() where U : T; }"); compilation.VerifyDiagnostics( // (4,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(4, 10), // (5,10): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(5, 10), // (10,10): error CS0111: Type 'I<T>' already defines a member called 'M' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "I<T>").WithLocation(10, 10)); } [Fact] public void CS0112ERR_StaticNotVirtual01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); } public class MyClass2 : MyClass { override public static void MyMethod() // CS0112, remove static keyword { } public static int Main() { return 0; } } } "; CreateCompilation(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,18): error CS0534: 'MyClass2' does not implement inherited abstract member 'MyClass.MyMethod()' // public class MyClass2 : MyClass Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "MyClass2").WithArguments("MyNamespace.MyClass2", "MyNamespace.MyClass.MyMethod()").WithLocation(7, 18), // (9,37): error CS0112: A static member cannot be marked as 'override' // override public static void MyMethod() // CS0112, remove static keyword Diagnostic(ErrorCode.ERR_StaticNotVirtual, "MyMethod").WithArguments("override").WithLocation(9, 37), // (9,37): warning CS0114: 'MyClass2.MyMethod()' hides inherited member 'MyClass.MyMethod()'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // override public static void MyMethod() // CS0112, remove static keyword Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "MyMethod").WithArguments("MyNamespace.MyClass2.MyMethod()", "MyNamespace.MyClass.MyMethod()").WithLocation(9, 37) ); } [Fact] public void CS0112ERR_StaticNotVirtual02() { var text = @"abstract class A { protected abstract object P { get; } } class B : A { protected static override object P { get { return null; } } public static virtual object Q { get; } internal static abstract object R { get; set; } } "; var tree = Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)); CreateCompilation(tree).VerifyDiagnostics( // (5,7): error CS0534: 'B' does not implement inherited abstract member 'A.P.get' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.P.get").WithLocation(5, 7), // (7,38): error CS0112: A static member cannot be marked as 'override' // protected static override object P { get { return null; } } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P").WithArguments("override").WithLocation(7, 38), // (7,38): warning CS0114: 'B.P' hides inherited member 'A.P'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected static override object P { get { return null; } } Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "P").WithArguments("B.P", "A.P").WithLocation(7, 38), // (8,34): error CS0112: A static member cannot be marked as 'virtual' // public static virtual object Q { get; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "Q").WithArguments("virtual").WithLocation(8, 34), // (8,34): error CS8026: Feature 'readonly automatically implemented properties' is not available in C# 5. Please use language version 6 or greater. // public static virtual object Q { get; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "Q").WithArguments("readonly automatically implemented properties", "6").WithLocation(8, 34), // (9,37): error CS0112: A static member cannot be marked as 'abstract' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_StaticNotVirtual, "R").WithArguments("abstract").WithLocation(9, 37), // (9,41): error CS0513: 'B.R.get' is abstract but it is contained in non-abstract type 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("B.R.get", "B").WithLocation(9, 41), // (9,46): error CS0513: 'B.R.set' is abstract but it is contained in non-abstract type 'B' // internal static abstract object R { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("B.R.set", "B").WithLocation(9, 46)); } [Fact] public void CS0112ERR_StaticNotVirtual03() { var text = @"abstract class A { protected abstract event System.Action P; } abstract class B : A { protected static override event System.Action P; public static virtual event System.Action Q; internal static abstract event System.Action R; } "; CreateCompilation(text, parseOptions: TestOptions.RegularPreview).VerifyDiagnostics( // (7,51): error CS0112: A static member cannot be marked as 'override' // protected static override event System.Action P; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "P").WithArguments("override").WithLocation(7, 51), // (7,51): error CS0533: 'B.P' hides inherited abstract member 'A.P' // protected static override event System.Action P; Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("B.P", "A.P").WithLocation(7, 51), // (7,51): warning CS0114: 'B.P' hides inherited member 'A.P'. To make the current member override that implementation, add the override keyword. Otherwise add the new keyword. // protected static override event System.Action P; Diagnostic(ErrorCode.WRN_NewOrOverrideExpected, "P").WithArguments("B.P", "A.P").WithLocation(7, 51), // (7,51): warning CS0067: The event 'B.P' is never used // protected static override event System.Action P; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P").WithArguments("B.P").WithLocation(7, 51), // (8,47): error CS0112: A static member cannot be marked as 'virtual' // public static virtual event System.Action Q; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "Q").WithArguments("virtual").WithLocation(8, 47), // (8,47): warning CS0067: The event 'B.Q' is never used // public static virtual event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("B.Q").WithLocation(8, 47), // (9,50): error CS0112: A static member cannot be marked as 'abstract' // internal static abstract event System.Action R; Diagnostic(ErrorCode.ERR_StaticNotVirtual, "R").WithArguments("abstract").WithLocation(9, 50) ); } [Fact] public void CS0113ERR_OverrideNotNew01() { var text = @"namespace MyNamespace { abstract public class MyClass { public abstract void MyMethod(); public abstract void MyMethod(int x); public virtual void MyMethod(int x, long j) { } } public class MyClass2 : MyClass { override new public void MyMethod() // CS0113, remove new keyword { } virtual override public void MyMethod(int x) // CS0113, remove virtual keyword { } virtual override public void MyMethod(int x, long j) // CS0113, remove virtual keyword { } public static int Main() { return 0; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 14, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 17, Column = 38 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 20, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew02() { var text = @"abstract class A { protected abstract object P { get; } internal virtual object Q { get; set; } } class B : A { protected new override object P { get { return null; } } internal virtual override object Q { get; set; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 8, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotNew, Line = 9, Column = 38 }); } [Fact] public void CS0113ERR_OverrideNotNew03() { var text = @"abstract class A { protected abstract event System.Action P; internal virtual event System.Action Q; } class B : A { protected new override event System.Action P; internal virtual override event System.Action Q; } "; CreateCompilation(text).VerifyDiagnostics( // (9,51): error CS0113: A member 'B.Q' marked as override cannot be marked as new or virtual // internal virtual override event System.Action Q; Diagnostic(ErrorCode.ERR_OverrideNotNew, "Q").WithArguments("B.Q").WithLocation(9, 51), // (8,48): error CS0113: A member 'B.P' marked as override cannot be marked as new or virtual // protected new override event System.Action P; Diagnostic(ErrorCode.ERR_OverrideNotNew, "P").WithArguments("B.P").WithLocation(8, 48), // (8,48): warning CS0067: The event 'B.P' is never used // protected new override event System.Action P; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "P").WithArguments("B.P").WithLocation(8, 48), // (9,51): warning CS0067: The event 'B.Q' is never used // internal virtual override event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("B.Q").WithLocation(9, 51), // (4,42): warning CS0067: The event 'A.Q' is never used // internal virtual event System.Action Q; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Q").WithArguments("A.Q").WithLocation(4, 42)); } [Fact] public void CS0115ERR_OverrideNotExpected() { var text = @"namespace MyNamespace { abstract public class MyClass1 { public abstract int f(); } abstract public class MyClass2 { public override int f() // CS0115 { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 29 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0118ERR_BadSKknown01() { var text = @"namespace NS { namespace Goo {} internal struct S { void Goo(Goo f) {} } class Bar { Goo foundNamespaceInsteadOfType; } public class A : Goo {} }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,18): error CS0118: 'Goo' is a namespace but is used like a type // void Goo(Goo f) {} Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (12,9): error CS0118: 'Goo' is a namespace but is used like a type // Goo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (15,22): error CS0118: 'Goo' is a namespace but is used like a type // public class A : Goo {} Diagnostic(ErrorCode.ERR_BadSKknown, "Goo").WithArguments("Goo", "namespace", "type"), // (12,13): warning CS0169: The field 'NS.Bar.foundNamespaceInsteadOfType' is never used // Goo foundNamespaceInsteadOfType; Diagnostic(ErrorCode.WRN_UnreferencedField, "foundNamespaceInsteadOfType").WithArguments("NS.Bar.foundNamespaceInsteadOfType") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = ns.GetTypeMembers("A").Single().BaseType(); Assert.Equal("Goo", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); Assert.Null(baseType.BaseType()); var type2 = ns.GetTypeMembers("Bar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers("foundNamespaceInsteadOfType").Single() as FieldSymbol; Assert.Equal("Goo", mem1.Type.Name); Assert.Equal(TypeKind.Error, mem1.Type.TypeKind); var type3 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type3.GetMembers("Goo").Single() as MethodSymbol; var param = mem2.Parameters[0]; Assert.Equal("Goo", param.Type.Name); Assert.Equal(TypeKind.Error, param.Type.TypeKind); } [WorkItem(538147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538147")] [Fact] public void CS0118ERR_BadSKknown02() { var text = @" class Test { static void Main() { B B = null; if (B == B) {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadSKknown, Line = 6, Column = 10 }); } [Fact] public void CS0119ERR_BadSKunknown01() { var text = @"namespace NS { using System; public class Test { public static void F() { } public static int Main() { Console.WriteLine(F.x); return NS(); } } }"; CreateCompilation(text).VerifyDiagnostics( // (10,31): error CS0119: 'NS.Test.F()' is a method, which is not valid in the given context // Console.WriteLine(F.x); Diagnostic(ErrorCode.ERR_BadSKunknown, "F").WithArguments("NS.Test.F()", "method"), // (11,20): error CS0118: 'NS' is a namespace but is used like a variable // return NS(); Diagnostic(ErrorCode.ERR_BadSKknown, "NS").WithArguments("NS", "namespace", "variable") ); } [Fact, WorkItem(538214, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538214")] public void CS0119ERR_BadSKunknown02() { var text = @"namespace N1 { class Test { static void Main() { double x = -5d; int y = (global::System.Int32) +x; short z = (System.Int16) +x; } } } "; // Roslyn gives same error twice CreateCompilation(text).VerifyDiagnostics( // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (8,22): error CS0119: 'int' is a type, which is not valid in the given context // int y = (global::System.Int32) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "global::System.Int32").WithArguments("int", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type"), // (9,24): error CS0119: 'short' is a type, which is not valid in the given context // short z = (System.Int16) +x; Diagnostic(ErrorCode.ERR_BadSKunknown, "System.Int16").WithArguments("short", "type") ); } [Fact] public void CS0132ERR_StaticConstParam01() { var text = @"namespace NS { struct S { static S(string s) { } } public class clx { static clx(params long[] ary) { } static clx(ref int n) { } } public class cly : clx { static cly() { } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 10, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstParam, Line = 11, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(539627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539627")] [Fact] public void CS0136ERR_LocalIllegallyOverrides() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @" class MyClass { public MyClass(int a) { long a; // 0136 } public long MyMeth(string x) { long x = 1; // 0136 return x; } public byte MyProp { set { int value; // 0136 } } } "; CreateCompilation(text). VerifyDiagnostics( Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "a").WithArguments("a"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "a").WithArguments("a"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x"), Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "value").WithArguments("value"), Diagnostic(ErrorCode.WRN_UnreferencedVar, "value").WithArguments("value") ); } [Fact] public void CS0136ERR_LocalIllegallyOverrides02() { // See comments in NameCollisionTests.cs for commentary on this error. var text = @"class C { public static void Main() { foreach (var x in ""abc"") { int x = 1 ; System.Console.WriteLine(x); } } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x")); } [Fact] public void CS0138ERR_BadUsingNamespace01() { var text = @"using System.Object; namespace NS { using NS.S; struct S {} }"; var comp = CreateCompilation(Parse(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); comp.VerifyDiagnostics( // (1,7): error CS0138: A using namespace directive can only be applied to namespaces; 'object' is a type not a namespace // using System.Object; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System.Object").WithArguments("object"), // (5,11): error CS0138: A using namespace directive can only be applied to namespaces; 'NS.S' is a type not a namespace // using NS.S; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "NS.S").WithArguments("NS.S"), // (1,1): info CS8019: Unnecessary using directive. // using System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Object;"), // (5,5): info CS8019: Unnecessary using directive. // using NS.S; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NS.S;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Roslyn has 3 extra CS0146, Neal said it's per spec /// </summary> [Fact] public void CS0146ERR_CircularBase01() { var text = @"namespace NS { class A : B { } class B : A { } public class AA : BB { } public class BB : CC { } public class CC : DD { } public class DD : BB { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 3, Column = 11 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 4, Column = 11 }, new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 7, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 8, Column = 18 }, // Roslyn extra new ErrorDescription { Code = (int)ErrorCode.ERR_CircularBase, Line = 9, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var baseType = (NamedTypeSymbol)ns.GetTypeMembers("A").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("B", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("DD").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("BB", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); baseType = (NamedTypeSymbol)ns.GetTypeMembers("BB").Single().BaseType(); Assert.Null(baseType.BaseType()); Assert.Equal("CC", baseType.Name); Assert.Equal(TypeKind.Error, baseType.TypeKind); } [Fact] public void CS0146ERR_CircularBase02() { var text = @"public interface C<T> { } public class D : C<D.Q> { private class Q { } // accessible in base clause } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase03() { var text = @" class A : object, A.IC { protected interface IC { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(4169, "DevDiv_Projects/Roslyn")] [Fact] public void CS0146ERR_CircularBase04() { var text = @" class A : object, I<A.IC> { protected interface IC { } } interface I<T> { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0179ERR_ExternHasBody01() { var text = @" namespace NS { public class C { extern C() { } extern void M1() { } extern int M2() => 1; extern object P1 { get { return null; } set { } } extern int P2 => 1; extern event System.Action E { add { } remove { } } extern static public int operator + (C c1, C c2) { return 1; } extern static public int operator - (C c1, C c2) => 1; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,16): error CS0179: 'C.C()' cannot be extern and declare a body // extern C() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "C").WithArguments("NS.C.C()").WithLocation(6, 16), // (7,21): error CS0179: 'C.M1()' cannot be extern and declare a body // extern void M1() { } Diagnostic(ErrorCode.ERR_ExternHasBody, "M1").WithArguments("NS.C.M1()").WithLocation(7, 21), // (8,20): error CS0179: 'C.M2()' cannot be extern and declare a body // extern int M2() => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "M2").WithArguments("NS.C.M2()").WithLocation(8, 20), // (9,28): error CS0179: 'C.P1.get' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "get").WithArguments("NS.C.P1.get").WithLocation(9, 28), // (9,49): error CS0179: 'C.P1.set' cannot be extern and declare a body // extern object P1 { get { return null; } set { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "set").WithArguments("NS.C.P1.set").WithLocation(9, 49), // (10,26): error CS0179: 'C.P2.get' cannot be extern and declare a body // extern int P2 => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "1").WithArguments("NS.C.P2.get").WithLocation(10, 26), // (11,40): error CS0179: 'C.E.add' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "add").WithArguments("NS.C.E.add").WithLocation(11, 40), // (11,48): error CS0179: 'C.E.remove' cannot be extern and declare a body // extern event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_ExternHasBody, "remove").WithArguments("NS.C.E.remove").WithLocation(11, 48), // (12,43): error CS0179: 'C.operator +(C, C)' cannot be extern and declare a body // extern static public int operator + (C c1, C c2) { return 1; } Diagnostic(ErrorCode.ERR_ExternHasBody, "+").WithArguments("NS.C.operator +(NS.C, NS.C)").WithLocation(12, 43), // (13,43): error CS0179: 'C.operator -(C, C)' cannot be extern and declare a body // extern static public int operator - (C c1, C c2) => 1; Diagnostic(ErrorCode.ERR_ExternHasBody, "-").WithArguments("NS.C.operator -(NS.C, NS.C)").WithLocation(13, 43)); } [Fact] public void CS0180ERR_AbstractAndExtern01() { CreateCompilation( @"abstract class X { public abstract extern void M(); public extern abstract int P { get; } // If a body is provided for an abstract extern method, // Dev10 reports CS0180, but does not report CS0179/CS0500. public abstract extern void N(int i) { } public extern abstract object Q { set { } } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("X.M()").WithLocation(3, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("X.P").WithLocation(4, 32), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "N").WithArguments("X.N(int)").WithLocation(7, 33), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "Q").WithArguments("X.Q").WithLocation(8, 35)); } [WorkItem(527618, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/527618")] [Fact] public void CS0180ERR_AbstractAndExtern02() { CreateCompilation( @"abstract class C { public extern abstract void M(); public extern abstract object P { set; } } ") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractAndExtern, "M").WithArguments("C.M()"), Diagnostic(ErrorCode.ERR_AbstractAndExtern, "P").WithArguments("C.P")); } [Fact] public void CS0180ERR_AbstractAndExtern03() { CreateCompilation( @"class C { public extern abstract event System.Action E; } ") .VerifyDiagnostics( // (3,48): error CS0180: 'C.E' cannot be both extern and abstract // public extern abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractAndExtern, "E").WithArguments("C.E")); } [Fact] public void CS0181ERR_BadAttributeParamType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1] // Dev11 error public class A1 : Attribute { public A1(dynamic i = null) { } } [A2] // Dev11 ok (bug) public class A2 : Attribute { public A2(dynamic[] i = null) { } } [A3] // Dev11 error (bug) public class A3 : Attribute { public A3(C<dynamic>.D i = 0) { } } [A4] // Dev11 ok public class A4 : Attribute { public A4(C<dynamic>.D[] i = null) { } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic', which is not a valid attribute parameter type // [A1] // Dev11 error Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A1").WithArguments("i", "dynamic"), // (12,2): error CS0181: Attribute constructor parameter 'i' has type 'dynamic[]', which is not a valid attribute parameter type // [A2] // Dev11 ok Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A2").WithArguments("i", "dynamic[]")); } [Fact] public void CS0182ERR_BadAttributeArgument() { var text = @"public class MyClass { static string s = ""Test""; [System.Diagnostics.ConditionalAttribute(s)] // CS0182 void NonConstantArgumentToConditional() { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,46): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [System.Diagnostics.ConditionalAttribute(s)] // CS0182 Diagnostic(ErrorCode.ERR_BadAttributeArgument, "s"), // (3,19): warning CS0414: The field 'MyClass.s' is assigned but its value is never used // static string s = "Test"; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("MyClass.s")); } [Fact] public void CS0214ERR_UnsafeNeeded() { var text = @"public struct S { public int a; } public class MyClass { public static void Test() { S s = new S(); S* s2 = &s; // CS0214 s2->a = 3; // CS0214 s.a = 0; } // OK unsafe public static void Test2() { S s = new S(); S* s2 = &s; s2->a = 3; s.a = 0; } } "; // NOTE: only first in scope is reported. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "S*"), // (11,17): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // S* s2 = &s; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "&s"), // (12,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s2->a = 3; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s2")); } [Fact] public void CS0214ERR_UnsafeNeeded02() { var text = @"unsafe struct S { public fixed int x[10]; } class Program { static void Main() { S s; s.x[1] = s.x[2]; } }"; // NOTE: only first in scope is reported. CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (11,9): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x"), // (11,18): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // s.x[1] = s.x[2]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "s.x")); } [Fact] public void CS0214ERR_UnsafeNeeded03() { var text = @"public struct S { public fixed int buf[10]; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed int buf[10]; Diagnostic(ErrorCode.ERR_UnsafeNeeded, "buf[10]")); } [Fact] public void CS0214ERR_UnsafeNeeded04() { var text = @" namespace System { public class TestType { public void TestMethod() { var x = stackalloc int[10]; // ERROR Span<int> y = stackalloc int[10]; // OK } } } "; CreateCompilationWithMscorlibAndSpan(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,21): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // var x = stackalloc int[10]; // ERROR Diagnostic(ErrorCode.ERR_UnsafeNeeded, "stackalloc int[10]").WithLocation(8, 21)); } [Fact] public void CS0215ERR_OpTFRetType() { var text = @"class MyClass { public static int operator true(MyClass MyInt) // CS0215 { return 1; } public static int operator false(MyClass MyInt) // CS0215 { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,32): error CS0215: The return type of operator True or False must be bool // public static int operator true(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "true"), // (8,32): error CS0215: The return type of operator True or False must be bool // public static int operator false(MyClass MyInt) // CS0215 Diagnostic(ErrorCode.ERR_OpTFRetType, "false") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch() { var text = @"class MyClass { // Missing operator false public static bool operator true(MyClass MyInt) // CS0216 { return true; } // Missing matching operator > -- parameter types must match. public static bool operator < (MyClass x, int y) { return false; } // Missing matching operator < -- parameter types must match. public static bool operator > (MyClass x, double y) { return false; } // Missing matching operator >= -- return types must match. public static MyClass operator <=(MyClass x, MyClass y) { return x; } // Missing matching operator <= -- return types must match. public static bool operator >=(MyClass x, MyClass y) { return true; } // Missing operator != public static bool operator ==(MyClass x, MyClass y) { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): warning CS0660: 'MyClass' defines operator == or operator != but does not override Object.Equals(object o) // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "MyClass").WithArguments("MyClass"), // (1,7): warning CS0661: 'MyClass' defines operator == or operator != but does not override Object.GetHashCode() // class MyClass Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "MyClass").WithArguments("MyClass"), // (4,33): error CS0216: The operator 'MyClass.operator true(MyClass)' requires a matching operator 'false' to also be defined // public static bool operator true(MyClass MyInt) // CS0216 Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "true").WithArguments("MyClass.operator true(MyClass)", "false"), // (73): error CS0216: The operator 'MyClass.operator <(MyClass, int)' requires a matching operator '>' to also be defined // public static bool operator < (MyClass x, int y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<").WithArguments("MyClass.operator <(MyClass, int)", ">"), // (10,33): error CS0216: The operator 'MyClass.operator >(MyClass, double)' requires a matching operator '<' to also be defined // public static bool operator > (MyClass x, double y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">").WithArguments("MyClass.operator >(MyClass, double)", "<"), // (13,36): error CS0216: The operator 'MyClass.operator <=(MyClass, MyClass)' requires a matching operator '>=' to also be defined // public static MyClass operator <=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "<=").WithArguments("MyClass.operator <=(MyClass, MyClass)", ">="), // (16,33): error CS0216: The operator 'MyClass.operator >=(MyClass, MyClass)' requires a matching operator '<=' to also be defined // public static bool operator >=(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, ">=").WithArguments("MyClass.operator >=(MyClass, MyClass)", "<="), // (19,33): error CS0216: The operator 'MyClass.operator ==(MyClass, MyClass)' requires a matching operator '!=' to also be defined // public static bool operator ==(MyClass x, MyClass y) Diagnostic(ErrorCode.ERR_OperatorNeedsMatch, "==").WithArguments("MyClass.operator ==(MyClass, MyClass)", "!=") ); } [Fact] public void CS0216ERR_OperatorNeedsMatch_NoErrorForDynamicObject() { string source = @" using System.Collections.Generic; class C { public static object operator >(C p1, dynamic p2) { return null; } public static dynamic operator <(C p1, object p2) { return null; } public static dynamic operator >=(C p1, dynamic p2) { return null; } public static object operator <=(C p1, object p2) { return null; } public static List<object> operator ==(C p1, dynamic[] p2) { return null; } public static List<dynamic> operator !=(C p1, object[] p2) { return null; } public override bool Equals(object o) { return false; } public override int GetHashCode() { return 1; } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0218ERR_MustHaveOpTF() { // Note that the wording of this error has changed. var text = @" public class MyClass { public static MyClass operator &(MyClass f1, MyClass f2) { return new MyClass(); } public static void Main() { MyClass f = new MyClass(); MyClass i = f && f; // CS0218, requires operators true and false } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,21): error CS0218: In order to be applicable as a short circuit operator, the declaring type 'MyClass' of user-defined operator 'MyClass.operator &(MyClass, MyClass)' must declare operator true and operator false. // MyClass i = f && f; // CS0218, requires operators true and false Diagnostic(ErrorCode.ERR_MustHaveOpTF, "f && f").WithArguments("MyClass.operator &(MyClass, MyClass)", "MyClass") ); } [Fact] public void CS0224ERR_BadVarargs01() { var text = @"namespace NS { class C { public static void F<T>(T x, __arglist) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 5, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0224ERR_BadVarargs02() { var text = @"class C { C(object o, __arglist) { } // no error void M(__arglist) { } // no error } abstract class C<T> { C(object o) { } // no error C(__arglist) { } void M(object o, __arglist) { } internal abstract object F(__arglist); } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 9, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 10, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadVarargs, Line = 11, Column = 30 }); } [Fact] public void CS0225ERR_ParamsMustBeArray01() { var text = @" using System.Collections.Generic; public class A { struct S { internal List<string> Bar(string s1, params List<string> s2) { return s2; } } public static void Goo(params int a) {} public static int Main() { Goo(1); return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 8, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParamsMustBeArray, Line = 13, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetTypeMembers("A").Single() as NamedTypeSymbol; // TODO... } [Fact] public void CS0227ERR_IllegalUnsafe() { var text = @"public class MyClass { unsafe public static void Main() // CS0227 { } } "; var c = CreateCompilation(text, options: TestOptions.ReleaseDll.WithAllowUnsafe(false)); c.VerifyDiagnostics( // (3,31): error CS0227: Unsafe code may only appear if compiling with /unsafe // unsafe public static void Main() // CS0227 Diagnostic(ErrorCode.ERR_IllegalUnsafe, "Main").WithLocation(3, 31)); } [Fact] public void CS0234ERR_DottedTypeNameNotFoundInNS() { var text = @"using NA = N.A; using NB = C<N.B<object>>; namespace N { } class C<T> { NA a; NB b; N.C<N.D> c; }"; CreateCompilation(text).VerifyDiagnostics( // (2,16): error CS0234: The type or namespace name 'B<>' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NB = C<N.B<object>>; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "B<object>").WithArguments("B<>", "N").WithLocation(2, 16), // (1,14): error CS0234: The type or namespace name 'A' does not exist in the namespace 'N' (are you missing an assembly reference?) // using NA = N.A; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "A").WithArguments("A", "N").WithLocation(1, 14), // (8,7): error CS0234: The type or namespace name 'C<>' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "C<N.D>").WithArguments("C<>", "N").WithLocation(8, 7), // (8,11): error CS0234: The type or namespace name 'D' does not exist in the namespace 'N' (are you missing an assembly reference?) // N.C<N.D> c; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "D").WithArguments("D", "N").WithLocation(8, 11), // (6,8): warning CS0169: The field 'C<T>.a' is never used // NA a; Diagnostic(ErrorCode.WRN_UnreferencedField, "a").WithArguments("C<T>.a").WithLocation(6, 8), // (7,8): warning CS0169: The field 'C<T>.b' is never used // NB b; Diagnostic(ErrorCode.WRN_UnreferencedField, "b").WithArguments("C<T>.b").WithLocation(7, 8), // (8,14): warning CS0169: The field 'C<T>.c' is never used // N.C<N.D> c; Diagnostic(ErrorCode.WRN_UnreferencedField, "c").WithArguments("C<T>.c").WithLocation(8, 14) ); } [Fact] public void CS0238ERR_SealedNonOverride01() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public sealed void f() // CS0238 { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 12, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 12, Column = 24, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 7 }); } [Fact] public void CS0238ERR_SealedNonOverride02() { var text = @"interface I { sealed void M(); sealed object P { get; } } "; //we're diverging from Dev10 - it's a little silly to report two errors saying the same modifier isn't allowed CreateCompilation(text, parseOptions: TestOptions.Regular7).VerifyDiagnostics( // (3,17): error CS8503: The modifier 'sealed' is not valid for this item in C# 7. Please use language version '8.0' or greater. // sealed void M(); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M").WithArguments("sealed", "7.0", "8.0").WithLocation(3, 17), // (4,19): error CS8503: The modifier 'sealed' is not valid for this item in C# 7. Please use language version '8.0' or greater. // sealed object P { get; } Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "P").WithArguments("sealed", "7.0", "8.0").WithLocation(4, 19), // (4,23): error CS0501: 'I.P.get' must declare a body because it is not marked abstract, extern, or partial // sealed object P { get; } Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("I.P.get").WithLocation(4, 23), // (3,17): error CS0501: 'I.M()' must declare a body because it is not marked abstract, extern, or partial // sealed void M(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("I.M()").WithLocation(3, 17) ); } [Fact] public void CS0238ERR_SealedNonOverride03() { var text = @"class B { sealed int P { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedNonOverride, Line = 3, Column = 16 }); } [Fact] public void CS0238ERR_SealedNonOverride04() { var text = @"class B { sealed event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (3,32): error CS0238: 'B.E' cannot be sealed because it is not an override // sealed event System.Action E; Diagnostic(ErrorCode.ERR_SealedNonOverride, "E").WithArguments("B.E"), // (3,32): warning CS0067: The event 'B.E' is never used // sealed event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B.E")); } [Fact] public void CS0239ERR_CantOverrideSealed() { var text = @"abstract class MyClass { public abstract void f(); } class MyClass2 : MyClass { public static void Main() { } public override sealed void f() { } } class MyClass3 : MyClass2 { public override void f() // CS0239 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideSealed, Line = 19, Column = 26 }); } [Fact()] public void CS0243ERR_ConditionalOnOverride() { var text = @"public class MyClass { public virtual void M() { } } public class MyClass2 : MyClass { [System.Diagnostics.ConditionalAttribute(""MySymbol"")] // CS0243 public override void M() { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,6): error CS0243: The Conditional attribute is not valid on 'MyClass2.M()' because it is an override method // [System.Diagnostics.ConditionalAttribute("MySymbol")] // CS0243 Diagnostic(ErrorCode.ERR_ConditionalOnOverride, @"System.Diagnostics.ConditionalAttribute(""MySymbol"")").WithArguments("MyClass2.M()").WithLocation(8, 6)); } [Fact] public void CS0246ERR_SingleTypeNameNotFound01() { var text = @"namespace NS { interface IGoo : INotExist {} // Extra CS0527 interface IBar { string M(ref NoType p1, out NoType p2, params NOType[] ary); } class A : CNotExist {} struct S { public const NoType field = 123; private NoType M() { return null; } } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 6, Column = 51 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 8, Column = 13 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 11, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 12, Column = 14 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("IGoo").Single() as NamedTypeSymbol; // bug: expected 1 but error symbol // Assert.Equal(1, type1.Interfaces().Count()); var type2 = ns.GetTypeMembers("IBar").Single() as NamedTypeSymbol; var mem1 = type2.GetMembers().First() as MethodSymbol; //ErrorTypes now appear as though they are declared in the global namespace. Assert.Equal("System.String NS.IBar.M(ref NoType p1, out NoType p2, params NOType[] ary)", mem1.ToTestDisplayString()); var param = mem1.Parameters[0] as ParameterSymbol; var ptype = param.TypeWithAnnotations; Assert.Equal(RefKind.Ref, param.RefKind); Assert.Equal(TypeKind.Error, ptype.Type.TypeKind); Assert.Equal("NoType", ptype.Type.Name); var type3 = ns.GetTypeMembers("A").Single() as NamedTypeSymbol; var base1 = type3.BaseType(); Assert.Null(base1.BaseType()); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("CNotExist", base1.Name); var type4 = ns.GetTypeMembers("S").Single() as NamedTypeSymbol; var mem2 = type4.GetMembers("field").First() as FieldSymbol; Assert.Equal(TypeKind.Error, mem2.Type.TypeKind); Assert.Equal("NoType", mem2.Type.Name); var mem3 = type4.GetMembers("M").Single() as MethodSymbol; Assert.Equal(TypeKind.Error, mem3.ReturnType.TypeKind); Assert.Equal("NoType", mem3.ReturnType.Name); } [WorkItem(537882, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537882")] [Fact] public void CS0246ERR_SingleTypeNameNotFound02() { var text = @"using NoExistNS1; namespace NS { using NoExistNS2; // No error for this one class Test { static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): error CS0246: The type or namespace name 'NoExistNS1' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS1").WithArguments("NoExistNS1"), // (5,11): error CS0246: The type or namespace name 'NoExistNS2' could not be found (are you missing a using directive or an assembly reference?) // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NoExistNS2").WithArguments("NoExistNS2"), // (1,1): info CS8019: Unnecessary using directive. // using NoExistNS1; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS1;"), // (5,5): info CS8019: Unnecessary using directive. // using NoExistNS2; // No error for this one Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NoExistNS2;")); } [Fact] public void CS0246ERR_SingleTypeNameNotFound03() { var text = @"[Attribute] class C { } "; CreateCompilation(text).VerifyDiagnostics( // (1,2): error CS0246: The type or namespace name 'AttributeAttribute' could not be found (are you missing a using directive or an assembly reference?) // [Attribute] class C { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("AttributeAttribute").WithLocation(1, 2), // (1,2): error CS0246: The type or namespace name 'Attribute' could not be found (are you missing a using directive or an assembly reference?) // [Attribute] class C { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Attribute").WithArguments("Attribute").WithLocation(1, 2)); } [Fact] public void CS0246ERR_SingleTypeNameNotFound04() { var text = @"class AAttribute : System.Attribute { } class BAttribute : System.Attribute { } [A][@B] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 5 }); } [Fact] public void CS0246ERR_SingleTypeNameNotFound05() { var text = @"class C { static void Main(string[] args) { System.Console.WriteLine(typeof(s)); // Invalid } } "; CreateCompilation(text). VerifyDiagnostics(Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "s").WithArguments("s")); } [WorkItem(543791, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543791")] [Fact] public void CS0246ERR_SingleTypeNameNotFound06() { var text = @"class C { public static Nada x = null, y = null; } "; CreateCompilation(text).VerifyDiagnostics( // (3,19): error CS0246: The type or namespace name 'Nada' could not be found (are you missing a using directive or an assembly reference?) // public static Nada x = null, y = null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Nada").WithArguments("Nada") ); } [Fact] public void CS0249ERR_OverrideFinalizeDeprecated() { var text = @"class MyClass { protected override void Finalize() // CS0249 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,29): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (3,29): error CS0249: Do not override object.Finalize. Instead, provide a destructor. Diagnostic(ErrorCode.ERR_OverrideFinalizeDeprecated, "Finalize")); } [Fact] public void CS0260ERR_MissingPartial01() { var text = @"namespace NS { public class C // CS0260 { partial struct S { } struct S { } // CS0260 } public partial class C {} public partial class C {} partial interface I {} interface I { } // CS0260 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 3, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 6, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_MissingPartial, Line = 13, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0261ERR_PartialTypeKindConflict01() { var text = @"namespace NS { partial class A { } partial class A { } partial struct A { } // CS0261 partial interface A { } // CS0261 partial class B { } partial struct B<T> { } partial interface B<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 5, Column = 20 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialTypeKindConflict, Line = 6, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0262ERR_PartialModifierConflict01() { var text = @"namespace NS { public partial interface I { } internal partial interface I { } partial interface I { } class A { internal partial class C { } protected partial class C {} private partial struct S { } internal partial struct S { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,30): error CS0262: Partial declarations of 'I' have conflicting accessibility modifiers // public partial interface I { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "I").WithArguments("NS.I").WithLocation(3, 30), // (9,32): error CS0262: Partial declarations of 'A.C' have conflicting accessibility modifiers // internal partial class C { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "C").WithArguments("NS.A.C").WithLocation(9, 32), // (12,32): error CS0262: Partial declarations of 'A.S' have conflicting accessibility modifiers // private partial struct S { } Diagnostic(ErrorCode.ERR_PartialModifierConflict, "S").WithArguments("NS.A.S").WithLocation(12, 32) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0263ERR_PartialMultipleBases01() { var text = @"namespace NS { class B1 { } class B2 { } partial class C : B1 // CS0263 - is the base class B1 or B2? { } partial class C : B2 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 5, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; var base1 = type1.BaseType(); Assert.Null(base1.BaseType()); Assert.Equal(TypeKind.Error, base1.TypeKind); Assert.Equal("B1", base1.Name); } [Fact] public void ERRMixed_BaseAnalysisMishmash() { var text = @"namespace NS { public interface I { } public class C { } public class D { } public struct S { } public struct N0 : object, NS.C { } public class N1 : C, D { } public struct N2 : C, D { } public class N3 : I, C { } public partial class N4 : C { } public partial class N4 : D { } class N5<T> : C, D { } class N6<T> : C, T { } class N7<T> : T, C { } interface N8 : I, I { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 8, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 10, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 11, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMultipleBases, Line = 13, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 16, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 17, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 18, Column = 19 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 18, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 20, Column = 23 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0264ERR_PartialWrongTypeParams01() { var text = @"namespace NS { public partial class C<T1> // CS0264.cs { } partial class C<T2> { partial struct S<X> { } // CS0264.cs partial struct S<T2> { } } internal partial interface IGoo<T, V> { } // CS0264.cs partial interface IGoo<T, U> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 3, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 9, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialWrongTypeParams, Line = 13, Column = 32 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("C").Single() as NamedTypeSymbol; Assert.Equal(1, type1.TypeParameters.Length); var param = type1.TypeParameters[0]; // Assert.Equal(TypeKind.Error, param.TypeKind); // this assert it incorrect: it is definitely a type parameter Assert.Equal("T1", param.Name); } [Fact] public void PartialMethodRenameParameters() { var text = @"namespace NS { public partial class MyClass { partial void F<T, U>(T t) where T : class; partial void F<T, U>(T tt) where T : class {} } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,22): warning CS8826: Partial method declarations 'void MyClass.F<T, U>(T t)' and 'void MyClass.F<T, U>(T tt)' have signature differences. // partial void F<T, U>(T tt) where T : class {} Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F").WithArguments("void MyClass.F<T, U>(T t)", "void MyClass.F<T, U>(T tt)").WithLocation(6, 22) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("MyClass").Single() as NamedTypeSymbol; Assert.Equal(0, type1.TypeParameters.Length); var f = type1.GetMembers("F").Single() as MethodSymbol; Assert.Equal("T t", f.Parameters[0].ToTestDisplayString()); } [Fact] public void PartialMethodRenameTypeParameters() { var text = @"namespace NS { public partial class MyClass { partial void F<T, U>(T t) where T : class; partial void F<U, T>(U u) where U : class {} } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,22): warning CS8826: Partial method declarations 'void MyClass.F<T, U>(T t)' and 'void MyClass.F<U, T>(U u)' have signature differences. // partial void F<U, T>(U u) where U : class {} Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "F").WithArguments("void MyClass.F<T, U>(T t)", "void MyClass.F<U, T>(U u)").WithLocation(6, 22) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetTypeMembers("MyClass").Single() as NamedTypeSymbol; Assert.Equal(0, type1.TypeParameters.Length); var f = type1.GetMembers("F").Single() as MethodSymbol; Assert.Equal(2, f.TypeParameters.Length); var param1 = f.TypeParameters[0]; var param2 = f.TypeParameters[1]; Assert.Equal("T", param1.Name); Assert.Equal("U", param2.Name); } [Fact] public void CS0265ERR_PartialWrongConstraints01() { var text = @"interface IA<T> { } interface IB { } // Different constraints. partial class A1<T> where T : struct { } partial class A1<T> where T : class { } partial class A2<T, U> where T : struct where U : IA<T> { } partial class A2<T, U> where T : class where U : IB { } partial class A3<T> where T : IA<T> { } partial class A3<T> where T : IA<IA<T>> { } partial interface A4<T> where T : struct, IB { } partial interface A4<T> where T : class, IB { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IA<T>, new() { } partial struct A5<T> where T : IB, new() { } // Additional constraints. partial class B1<T> where T : new() { } partial class B1<T> where T : class, new() { } partial class B2<T, U> where T : IA<T> { } partial class B2<T, U> where T : IB, IA<T> { } // Missing constraints. partial interface C1<T> where T : class, new() { } partial interface C1<T> where T : new() { } partial struct C2<T, U> where U : IB, IA<T> { } partial struct C2<T, U> where U : IA<T> { } // Same constraints, different order. partial class D1<T> where T : IA<T>, IB { } partial class D1<T> where T : IB, IA<T> { } partial class D1<T> where T : IA<T>, IB { } partial class D2<T, U, V> where V : T, U { } partial class D2<T, U, V> where V : U, T { } // Different constraint clauses. partial class E1<T, U> where U : T { } partial class E1<T, U> where T : class { } partial class E1<T, U> where U : T { } partial class E2<T, U> where U : IB { } partial class E2<T, U> where T : IA<U> { } partial class E2<T, U> where T : IA<U> { } // Additional constraint clause. partial class F1<T> { } partial class F1<T> { } partial class F1<T> where T : class { } partial class F2<T> { } partial class F2<T, U> where T : class { } partial class F2<T, U> where T : class where U : T { } // Missing constraint clause. partial interface G1<T> where T : class { } partial interface G1<T> { } partial struct G2<T, U> where T : class where U : T { } partial struct G2<T, U> where T : class { } partial struct G2<T, U> { } // Same constraint clauses, different order. partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where T : class where U : T { } partial class H1<T, U> where U : T where T : class { } partial class H2<T, U, V> where U : IB where T : IA<V> { } partial class H2<T, U, V> where T : IA<V> where U : IB { }"; CreateCompilation(text).VerifyDiagnostics( // (4,15): error CS0265: Partial declarations of 'A1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A1").WithArguments("A1<T>", "T").WithLocation(4, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "T").WithLocation(6, 15), // (6,15): error CS0265: Partial declarations of 'A2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A2").WithArguments("A2<T, U>", "U").WithLocation(6, 15), // (8,15): error CS0265: Partial declarations of 'A3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A3").WithArguments("A3<T>", "T").WithLocation(8, 15), // (10,19): error CS0265: Partial declarations of 'A4<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A4").WithArguments("A4<T>", "T").WithLocation(10, 19), // (12,16): error CS0265: Partial declarations of 'A5<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "A5").WithArguments("A5<T>", "T").WithLocation(12, 16), // (16,15): error CS0265: Partial declarations of 'B1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B1").WithArguments("B1<T>", "T").WithLocation(16, 15), // (18,15): error CS0265: Partial declarations of 'B2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B2").WithArguments("B2<T, U>", "T").WithLocation(18, 15), // (21,19): error CS0265: Partial declarations of 'C1<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C1").WithArguments("C1<T>", "T").WithLocation(21, 19), // (23,16): error CS0265: Partial declarations of 'C2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C2").WithArguments("C2<T, U>", "U").WithLocation(23, 16), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "T").WithLocation(32, 15), // (32,15): error CS0265: Partial declarations of 'E1<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E1").WithArguments("E1<T, U>", "U").WithLocation(32, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "T").WithLocation(35, 15), // (35,15): error CS0265: Partial declarations of 'E2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "E2").WithArguments("E2<T, U>", "U").WithLocation(35, 15), // (43,15): error CS0265: Partial declarations of 'F2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "F2").WithArguments("F2<T, U>", "U").WithLocation(43, 15), // (48,16): error CS0265: Partial declarations of 'G2<T, U>' have inconsistent constraints for type parameter 'U' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "G2").WithArguments("G2<T, U>", "U").WithLocation(48, 16)); } [Fact] public void CS0265ERR_PartialWrongConstraints02() { var text = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class B1<T> where T : A, IB<IA> { } partial class B1<T> where T : N.A, N.IB<N.IA> { } partial class B1<T> where T : NA1, NIBA { } partial class B2<T> where T : NA1, IB<A.IC> { } partial class B2<T> where T : NA2, NIBAC { } partial class B3<T> where T : IB<A> { } partial class B3<T> where T : NIBA { } }"; CreateCompilation(text).VerifyDiagnostics( // (19,19): error CS0265: Partial declarations of 'N.B3<T>' have inconsistent constraints for type parameter 'T' Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B3").WithArguments("N.B3<T>", "T").WithLocation(19, 19), // (1,1): info CS8019: Unnecessary using directive. // using NIA = N.IA; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using NIA = N.IA;").WithLocation(1, 1)); } /// <summary> /// Class1.dll: error CS0268: Imported type 'C1' is invalid. It contains a circular base type dependency. /// </summary> [Fact()] public void CS0268ERR_ImportedCircularBase01() { var text = @"namespace NS { public class C3 : C1 { } public interface I3 : I1 { } } "; var ref1 = TestReferences.SymbolsTests.CyclicInheritance.Class1; var ref2 = TestReferences.SymbolsTests.CyclicInheritance.Class2; var comp = CreateCompilation(text, new[] { ref1, ref2 }); comp.VerifyDiagnostics( // (3,23): error CS0268: Imported type 'C2' is invalid. It contains a circular base type dependency. // public class C3 : C1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "C1").WithArguments("C2", "C1"), // (4,22): error CS0268: Imported type 'I2' is invalid. It contains a circular base type dependency. // public interface I3 : I1 { } Diagnostic(ErrorCode.ERR_ImportedCircularBase, "I3").WithArguments("I2", "I1") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0273ERR_InvalidPropertyAccessMod() { var text = @"class C { public object P1 { get; public set; } // CS0273 public object P2 { get; internal set; } public object P3 { get; protected set; } public object P4 { get; protected internal set; } public object P5 { get; private set; } internal object Q1 { public get; set; } // CS0273 internal object Q2 { internal get; set; } // CS0273 internal object Q3 { protected get; set; } // CS0273 internal object Q4 { protected internal get; set; } // CS0273 internal object Q5 { private get; set; } protected object R1 { get { return null; } public set { } } // CS0273 protected object R2 { get { return null; } internal set { } } // CS0273 protected object R3 { get { return null; } protected set { } } // CS0273 protected object R4 { get { return null; } protected internal set { } } // CS0273 protected object R5 { get { return null; } private set { } } protected internal object S1 { get { return null; } public set { } } // CS0273 protected internal object S2 { get { return null; } internal set { } } protected internal object S3 { get { return null; } protected set { } } protected internal object S4 { get { return null; } protected internal set { } } // CS0273 protected internal object S5 { get { return null; } private set { } } private object T1 { public get; set; } // CS0273 private object T2 { internal get; set; } // CS0273 private object T3 { protected get; set; } // CS0273 private object T4 { protected internal get; set; } // CS0273 private object T5 { private get; set; } // CS0273 object U1 { public get; set; } // CS0273 object U2 { internal get; set; } // CS0273 object U3 { protected get; set; } // CS0273 object U4 { protected internal get; set; } // CS0273 object U5 { private get; set; } // CS0273 } "; CreateCompilation(text).VerifyDiagnostics( // (3,36): error CS0273: The accessibility modifier of the 'C.P1.set' accessor must be more restrictive than the property or indexer 'C.P1' // public object P1 { get; public set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.P1.set", "C.P1"), // (8,33): error CS0273: The accessibility modifier of the 'C.Q1.get' accessor must be more restrictive than the property or indexer 'C.Q1' // internal object Q1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q1.get", "C.Q1"), // (9,35): error CS0273: The accessibility modifier of the 'C.Q2.get' accessor must be more restrictive than the property or indexer 'C.Q2' // internal object Q2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q2.get", "C.Q2"), // (10,36): error CS0273: The accessibility modifier of the 'C.Q3.get' accessor must be more restrictive than the property or indexer 'C.Q3' // internal object Q3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q3.get", "C.Q3"), // (11,45): error CS0273: The accessibility modifier of the 'C.Q4.get' accessor must be more restrictive than the property or indexer 'C.Q4' // internal object Q4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.Q4.get", "C.Q4"), // (13,55): error CS0273: The accessibility modifier of the 'C.R1.set' accessor must be more restrictive than the property or indexer 'C.R1' // protected object R1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R1.set", "C.R1"), // (14,57): error CS0273: The accessibility modifier of the 'C.R2.set' accessor must be more restrictive than the property or indexer 'C.R2' // protected object R2 { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R2.set", "C.R2"), // (15,58): error CS0273: The accessibility modifier of the 'C.R3.set' accessor must be more restrictive than the property or indexer 'C.R3' // protected object R3 { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R3.set", "C.R3"), // (16,67): error CS0273: The accessibility modifier of the 'C.R4.set' accessor must be more restrictive than the property or indexer 'C.R4' // protected object R4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.R4.set", "C.R4"), // (18,64): error CS0273: The accessibility modifier of the 'C.S1.set' accessor must be more restrictive than the property or indexer 'C.S1' // protected internal object S1 { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S1.set", "C.S1"), // (21,76): error CS0273: The accessibility modifier of the 'C.S4.set' accessor must be more restrictive than the property or indexer 'C.S4' // protected internal object S4 { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.S4.set", "C.S4"), // (23,32): error CS0273: The accessibility modifier of the 'C.T1.get' accessor must be more restrictive than the property or indexer 'C.T1' // private object T1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T1.get", "C.T1"), // (24,34): error CS0273: The accessibility modifier of the 'C.T2.get' accessor must be more restrictive than the property or indexer 'C.T2' // private object T2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T2.get", "C.T2"), // (25,35): error CS0273: The accessibility modifier of the 'C.T3.get' accessor must be more restrictive than the property or indexer 'C.T3' // private object T3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T3.get", "C.T3"), // (26,44): error CS0273: The accessibility modifier of the 'C.T4.get' accessor must be more restrictive than the property or indexer 'C.T4' // private object T4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T4.get", "C.T4"), // (273): error CS0273: The accessibility modifier of the 'C.T5.get' accessor must be more restrictive than the property or indexer 'C.T5' // private object T5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.T5.get", "C.T5"), // (28,24): error CS0273: The accessibility modifier of the 'C.U1.get' accessor must be more restrictive than the property or indexer 'C.U1' // object U1 { public get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U1.get", "C.U1"), // (29,26): error CS0273: The accessibility modifier of the 'C.U2.get' accessor must be more restrictive than the property or indexer 'C.U2' // object U2 { internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U2.get", "C.U2"), // (30,27): error CS0273: The accessibility modifier of the 'C.U3.get' accessor must be more restrictive than the property or indexer 'C.U3' // object U3 { protected get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U3.get", "C.U3"), // (31,36): error CS0273: The accessibility modifier of the 'C.U4.get' accessor must be more restrictive than the property or indexer 'C.U4' // object U4 { protected internal get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U4.get", "C.U4"), // (32,25): error CS0273: The accessibility modifier of the 'C.U5.get' accessor must be more restrictive than the property or indexer 'C.U5' // object U5 { private get; set; } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.U5.get", "C.U5")); } [Fact] public void CS0273ERR_InvalidPropertyAccessMod_Indexers() { var text = @"class C { public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 public object this[int x, double y, int z] { get { return null; } internal set { } } public object this[int x, double y, double z] { get { return null; } protected set { } } public object this[double x, int y, int z] { get { return null; } protected internal set { } } public object this[double x, int y, double z] { get { return null; } private set { } } internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 internal object this[char x, int y, char z] { private get { return null; } set { } } protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected object this[long x, int y, long z] { get { return null; } private set { } } protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 protected internal object this[int x, float y, int z] { get { return null; } internal set { } } protected internal object this[int x, float y, float z] { get { return null; } protected set { } } protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 protected internal object this[float x, int y, float z] { get { return null; } private set { } } private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 } "; CreateCompilation(text).VerifyDiagnostics( // (3,78): error CS0273: The accessibility modifier of the 'C.this[int, int, double].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, double]' // public object this[int x, int y, double z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, double].set", "C.this[int, int, double]"), // (8,57): error CS0273: The accessibility modifier of the 'C.this[int, int, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, char]' // internal object this[int x, int y, char z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, char].get", "C.this[int, int, char]"), // (9,59): error CS0273: The accessibility modifier of the 'C.this[int, char, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, int]' // internal object this[int x, char y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, int].get", "C.this[int, char, int]"), // (10,61): error CS0273: The accessibility modifier of the 'C.this[int, char, char].get' accessor must be more restrictive than the property or indexer 'C.this[int, char, char]' // internal object this[int x, char y, char z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, char, char].get", "C.this[int, char, char]"), // (11,69): error CS0273: The accessibility modifier of the 'C.this[char, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[char, int, int]' // internal object this[char x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[char, int, int].get", "C.this[char, int, int]"), // (13,79): error CS0273: The accessibility modifier of the 'C.this[int, int, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, long]' // protected object this[int x, int y, long z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, long].set", "C.this[int, int, long]"), // (14,81): error CS0273: The accessibility modifier of the 'C.this[int, long, int].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, int]' // protected object this[int x, long y, int z] { get { return null; } internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, int].set", "C.this[int, long, int]"), // (15,83): error CS0273: The accessibility modifier of the 'C.this[int, long, long].set' accessor must be more restrictive than the property or indexer 'C.this[int, long, long]' // protected object this[int x, long y, long z] { get { return null; } protected set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, long, long].set", "C.this[int, long, long]"), // (16,91): error CS0273: The accessibility modifier of the 'C.this[long, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[long, int, int]' // protected object this[long x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[long, int, int].set", "C.this[long, int, int]"), // (18,89): error CS0273: The accessibility modifier of the 'C.this[int, int, float].set' accessor must be more restrictive than the property or indexer 'C.this[int, int, float]' // protected internal object this[int x, int y, float z] { get { return null; } public set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[int, int, float].set", "C.this[int, int, float]"), // (21,101): error CS0273: The accessibility modifier of the 'C.this[float, int, int].set' accessor must be more restrictive than the property or indexer 'C.this[float, int, int]' // protected internal object this[float x, int y, int z] { get { return null; } protected internal set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "set").WithArguments("C.this[float, int, int].set", "C.this[float, int, int]"), // (23,58): error CS0273: The accessibility modifier of the 'C.this[int, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, string]' // private object this[int x, int y, string z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, string].get", "C.this[int, int, string]"), // (24,60): error CS0273: The accessibility modifier of the 'C.this[int, string, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, int]' // private object this[int x, string y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, int].get", "C.this[int, string, int]"), // (25,64): error CS0273: The accessibility modifier of the 'C.this[int, string, string].get' accessor must be more restrictive than the property or indexer 'C.this[int, string, string]' // private object this[int x, string y, string z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, string, string].get", "C.this[int, string, string]"), // (26,70): error CS0273: The accessibility modifier of the 'C.this[string, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, int]' // private object this[string x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, int].get", "C.this[string, int, int]"), // (27,62): error CS0273: The accessibility modifier of the 'C.this[string, int, string].get' accessor must be more restrictive than the property or indexer 'C.this[string, int, string]' // private object this[string x, int y, string z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[string, int, string].get", "C.this[string, int, string]"), // (28,50): error CS0273: The accessibility modifier of the 'C.this[int, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, int, object]' // object this[int x, int y, object z] { public get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, int, object].get", "C.this[int, int, object]"), // (29,52): error CS0273: The accessibility modifier of the 'C.this[int, object, int].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, int]' // object this[int x, object y, int z] { internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, int].get", "C.this[int, object, int]"), // (30,56): error CS0273: The accessibility modifier of the 'C.this[int, object, object].get' accessor must be more restrictive than the property or indexer 'C.this[int, object, object]' // object this[int x, object y, object z] { protected get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[int, object, object].get", "C.this[int, object, object]"), // (31,62): error CS0273: The accessibility modifier of the 'C.this[object, int, int].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, int]' // object this[object x, int y, int z] { protected internal get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, int].get", "C.this[object, int, int]"), // (32,54): error CS0273: The accessibility modifier of the 'C.this[object, int, object].get' accessor must be more restrictive than the property or indexer 'C.this[object, int, object]' // object this[object x, int y, object z] { private get { return null; } set { } } // CS0273 Diagnostic(ErrorCode.ERR_InvalidPropertyAccessMod, "get").WithArguments("C.this[object, int, object].get", "C.this[object, int, object]")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods() { var text = @"class C { public int P { protected get; internal set; } internal object Q { private get { return null; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.P' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "P").WithArguments("C.P"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.Q' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "Q").WithArguments("C.Q")); } [Fact] public void CS0274ERR_DuplicatePropertyAccessMods_Indexer() { var text = @"class C { public int this[int x] { protected get { return 0; } internal set { } } internal object this[object x] { private get { return null; } private set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,16): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[int]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[int]"), // (4,21): error CS0274: Cannot specify accessibility modifiers for both accessors of the property or indexer 'C.this[object]' Diagnostic(ErrorCode.ERR_DuplicatePropertyAccessMods, "this").WithArguments("C.this[object]")); } [Fact] public void CS0275ERR_PropertyAccessModInInterface() { CreateCompilation( @"interface I { object P { get; } // no error int Q { private get; set; } // CS0275 object R { get; internal set; } // CS0275 } ", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (4,21): error CS8503: The modifier 'private' is not valid for this item in C# 7. Please use language version '8.0' or greater. // int Q { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.0", "8.0").WithLocation(4, 21), // (4,21): error CS0442: 'I.Q.get': abstract properties cannot have private accessors // int Q { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I.Q.get").WithLocation(4, 21), // (5,30): error CS8503: The modifier 'internal' is not valid for this item in C# 7. Please use language version '8.0' or greater. // object R { get; internal set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.0", "8.0").WithLocation(5, 30) ); } [Fact] public void CS0275ERR_PropertyAccessModInInterface_Indexer() { CreateCompilation( @"interface I { object this[int x] { get; } // no error int this[char x] { private get; set; } // CS0275 object this[string x] { get; internal set; } // CS0275 } ", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (4,32): error CS8503: The modifier 'private' is not valid for this item in C# 7. Please use language version '8.0' or greater. // int this[char x] { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "get").WithArguments("private", "7.0", "8.0").WithLocation(4, 32), // (4,32): error CS0442: 'I.this[char].get': abstract properties cannot have private accessors // int this[char x] { private get; set; } // CS0275 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("I.this[char].get").WithLocation(4, 32), // (5,43): error CS8503: The modifier 'internal' is not valid for this item in C# 7. Please use language version '8.0' or greater. // object this[string x] { get; internal set; } // CS0275 Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "set").WithArguments("internal", "7.0", "8.0").WithLocation(5, 43) ); } [WorkItem(538620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538620")] [Fact] public void CS0276ERR_AccessModMissingAccessor() { var text = @"class A { public virtual object P { get; protected set; } } class B : A { public override object P { protected set { } } // no error public object Q { private set { } } // CS0276 protected internal object R { internal get { return null; } } // CS0276 } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.Q': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "Q").WithArguments("B.Q"), // (9,31): error CS0276: 'B.R': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "R").WithArguments("B.R")); } [Fact] public void CS0276ERR_AccessModMissingAccessor_Indexer() { var text = @"class A { public virtual object this[int x] { get { return null; } protected set { } } } class B : A { public override object this[int x] { protected set { } } // no error public object this[char x] { private set { } } // CS0276 protected internal object this[string x] { internal get { return null; } } // CS0276 } "; CreateCompilation(text).VerifyDiagnostics( // (8,19): error CS0276: 'B.this[char]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[char]"), // (9,31): error CS0276: 'B.this[string]': accessibility modifiers on accessors may only be used if the property or indexer has both a get and a set accessor Diagnostic(ErrorCode.ERR_AccessModMissingAccessor, "this").WithArguments("B.this[string]")); } [Fact] public void CS0277ERR_UnimplementedInterfaceAccessor() { var text = @"public interface MyInterface { int Property { get; set; } } public class MyClass : MyInterface // CS0277 { public int Property { get { return 0; } protected set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceAccessor, Line = 10, Column = 24 }); } [Fact(Skip = "530901"), WorkItem(530901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530901")] public void CS0281ERR_FriendRefNotEqualToThis() { //sn -k CS0281.snk //sn -i CS0281.snk CS0281.snk //sn -pc CS0281.snk key.publickey //sn -tp key.publickey //csc /target:library /keyfile:CS0281.snk class1.cs //csc /target:library /keyfile:CS0281.snk /reference:class1.dll class2.cs //csc /target:library /keyfile:CS0281.snk /reference:class2.dll /out:class1.dll program.cs var text1 = @"public class A { }"; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); var text2 = @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""Class1 , PublicKey=abc"")] class B : A { } "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); var text3 = @"using System.Runtime.CompilerServices; [assembly: System.Reflection.AssemblyVersion(""3"")] [assembly: System.Reflection.AssemblyCulture(""en-us"")] [assembly: InternalsVisibleTo(""MyServices, PublicKeyToken=aaabbbcccdddeee"")] class C : B { } public class A { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text3, new ErrorDescription { Code = (int)ErrorCode.ERR_FriendRefNotEqualToThis, Line = 10, Column = 14 }); } /// <summary> /// Some? /// </summary> [Fact] public void CS0305ERR_BadArity01() { var text = @"namespace NS { interface I<T, V> { } struct S<T> : I<T> { } class C<T> { } public class Test { //public static int Main() //{ // C c = new C(); // Not in Dev10 // return 1; //} I<T, V, U> M<T, V, U>() { return null; } public I<int> field; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 5, Column = 19 }, //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 13 }, // Dev10 miss this due to other errors //new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 13, Column = 23 }, // Dev10 miss this due to other errors new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 17, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadArity, Line = 18, Column = 16 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0306ERR_BadTypeArgument01() { var source = @"using System; class C<T> { static void F<U>() { } static void M(object o) { new C<int*>(); new C<ArgIterator>(); new C<RuntimeArgumentHandle>(); new C<TypedReference>(); F<int*>(); o.E<object, ArgIterator>(); Action a; a = F<RuntimeArgumentHandle>; a = o.E<T, TypedReference>; Console.WriteLine(typeof(TypedReference?)); Console.WriteLine(typeof(Nullable<TypedReference>)); } } static class S { internal static void E<T, U>(this object o) { } } "; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (7,15): error CS0306: The type 'int*' may not be used as a type argument // new C<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "int*").WithArguments("int*").WithLocation(7, 15), // (8,15): error CS0306: The type 'ArgIterator' may not be used as a type argument // new C<ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "ArgIterator").WithArguments("System.ArgIterator").WithLocation(8, 15), // (9,15): error CS0306: The type 'RuntimeArgumentHandle' may not be used as a type argument // new C<RuntimeArgumentHandle>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(9, 15), // (10,15): error CS0306: The type 'TypedReference' may not be used as a type argument // new C<TypedReference>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(10, 15), // (11,9): error CS0306: The type 'int*' may not be used as a type argument // F<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<int*>").WithArguments("int*").WithLocation(11, 9), // (12,11): error CS0306: The type 'ArgIterator' may not be used as a type argument // o.E<object, ArgIterator>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "E<object, ArgIterator>").WithArguments("System.ArgIterator").WithLocation(12, 11), // (14,13): error CS0306: The type 'RuntimeArgumentHandle' may not be used as a type argument // a = F<RuntimeArgumentHandle>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<RuntimeArgumentHandle>").WithArguments("System.RuntimeArgumentHandle").WithLocation(14, 13), // (15,13): error CS0306: The type 'TypedReference' may not be used as a type argument // a = o.E<T, TypedReference>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "o.E<T, TypedReference>").WithArguments("System.TypedReference").WithLocation(15, 13), // (16,34): error CS0306: The type 'TypedReference' may not be used as a type argument // Console.WriteLine(typeof(TypedReference?)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference?").WithArguments("System.TypedReference").WithLocation(16, 34), // (17,43): error CS0306: The type 'TypedReference' may not be used as a type argument // Console.WriteLine(typeof(Nullable<TypedReference>)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "TypedReference").WithArguments("System.TypedReference").WithLocation(17, 43)); } /// <summary> /// Bad type arguments for aliases should be reported at the /// alias declaration rather than at the use. (Note: This differs /// from Dev10 which reports errors at the use, with no errors /// reported if there are no uses of the alias.) /// </summary> [Fact] public void CS0306ERR_BadTypeArgument02() { var source = @"using COfObject = C<object>; using COfIntPtr = C<int*>; using COfArgIterator = C<System.ArgIterator>; // unused class C<T> { static void F<U>() { } static void M() { new COfIntPtr(); COfObject.F<int*>(); COfIntPtr.F<object>(); } }"; CreateCompilationWithMscorlib46(source).VerifyDiagnostics( // (3,7): error CS0306: The type 'ArgIterator' may not be used as a type argument // using COfArgIterator = C<System.ArgIterator>; // unused Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfArgIterator").WithArguments("System.ArgIterator").WithLocation(3, 7), // (2,7): error CS0306: The type 'int*' may not be used as a type argument // using COfIntPtr = C<int*>; Diagnostic(ErrorCode.ERR_BadTypeArgument, "COfIntPtr").WithArguments("int*").WithLocation(2, 7), // (10,19): error CS0306: The type 'int*' may not be used as a type argument // COfObject.F<int*>(); Diagnostic(ErrorCode.ERR_BadTypeArgument, "F<int*>").WithArguments("int*").WithLocation(10, 19), // (3,1): hidden CS8019: Unnecessary using directive. // using COfArgIterator = C<System.ArgIterator>; // unused Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using COfArgIterator = C<System.ArgIterator>;").WithLocation(3, 1)); } [WorkItem(538157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538157")] [Fact] public void CS0307ERR_TypeArgsNotAllowed() { var text = @"namespace NS { public class Test<T> { internal object field; public int P { get { return 1; } } public static int Main() { Test<int> t = new NS<T>.Test<int>(); var v = t.field<string>; int p = t.P<int>(); if (v == v | p == p | t == t) {} return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (10,31): error CS0307: The namespace 'NS' cannot be used with type arguments // Test<int> t = new NS<T>.Test<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "NS<T>").WithArguments("NS", "namespace"), // (11,23): error CS0307: The field 'NS.Test<int>.field' cannot be used with type arguments // var v = t.field<string>; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "field<string>").WithArguments("NS.Test<int>.field", "field"), // (12,23): error CS0307: The property 'NS.Test<int>.P' cannot be used with type arguments // int p = t.P<int>(); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "P<int>").WithArguments("NS.Test<int>.P", "property"), // (13,17): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "v == v"), // (13,26): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "p == p"), // (13,35): warning CS1718: Comparison made to same variable; did you mean to compare something else? // if (v == v | p == p | t == t) {} Diagnostic(ErrorCode.WRN_ComparisonToSelf, "t == t"), // (5,25): warning CS0649: Field 'NS.Test<T>.field' is never assigned to, and will always have its default value null // internal object field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Test<T>.field", "null") ); } [WorkItem(542296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542296")] [Fact] public void CS0307ERR_TypeArgsNotAllowed_02() { var text = @" public class Test { public int Fld; public int Func() { return (int)(Fld<int>); } } "; CreateCompilation(text).VerifyDiagnostics( // (7,22): error CS0307: The field 'Test.Fld' cannot be used with type arguments // return (int)(Fld<int>); Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "Fld<int>").WithArguments("Test.Fld", "field") ); } [Fact] public void CS0307ERR_TypeArgsNotAllowed_03() { var text = @"class C<T, U> where T : U<T>, new() { static object M() { return new T<U>(); } }"; CreateCompilation(text).VerifyDiagnostics( // (1,25): error CS0307: The type parameter 'U' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "U<T>").WithArguments("U", "type parameter").WithLocation(1, 25), // (5,20): error CS0307: The type parameter 'T' cannot be used with type arguments Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "T<U>").WithArguments("T", "type parameter").WithLocation(5, 20)); } [Fact] public void CS0308ERR_HasNoTypeVars01() { var text = @"namespace NS { public class Test { public static string F() { return null; } protected void FF(string s) { } public static int Main() { new Test().FF<string, string>(F<int>()); return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 10, Column = 43 }); } [WorkItem(540090, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540090")] [Fact] public void CS0308ERR_HasNoTypeVars02() { var text = @" public class NormalType { public static class M2 { public static int F1 = 1; } public static void Test() { int i; i = M2<int>.F1; } public static int Main() { return -1; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HasNoTypeVars, Line = 8, Column = 13 }); } [Fact] public void CS0400ERR_GlobalSingleTypeNameNotFound01() { var text = @"namespace NS { public class Test { public static int Main() { // global::D d = new global::D(); return 1; } } struct S { global::G field; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,17): error CS0400: The type or namespace name 'G' could not be found in the global namespace (are you missing an assembly reference?) // global::G field; Diagnostic(ErrorCode.ERR_GlobalSingleTypeNameNotFound, "G").WithArguments("G", "<global namespace>"), // (14,19): warning CS0169: The field 'NS.S.field' is never used // global::G field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0405ERR_DuplicateBound() { var source = @"interface IA { } interface IB { } class A { } class B { } class C<T, U> where T : IA, IB, IA where U : A, IA, A { void M<V>() where V : U, IA, U { } }"; CreateCompilation(source).VerifyDiagnostics( // (6,23): error CS0405: Duplicate constraint 'IA' for type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateBound, "IA").WithArguments("IA", "T").WithLocation(6, 23), // (7,22): error CS0405: Duplicate constraint 'A' for type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateBound, "A").WithArguments("A", "U").WithLocation(7, 22), // (9,34): error CS0405: Duplicate constraint 'U' for type parameter 'V' Diagnostic(ErrorCode.ERR_DuplicateBound, "U").WithArguments("U", "V").WithLocation(9, 34)); } [Fact] public void CS0406ERR_ClassBoundNotFirst() { var source = @"interface I { } class A { } class B { } class C<T, U> where T : I, A where U : A, B { void M<V>() where V : U, A, B { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,18): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(5, 18), // (6,18): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(6, 18), // (8,30): error CS0406: The class type constraint 'A' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "A").WithArguments("A").WithLocation(8, 30), // (8,33): error CS0406: The class type constraint 'B' must come before any other constraints Diagnostic(ErrorCode.ERR_ClassBoundNotFirst, "B").WithArguments("B").WithLocation(8, 33)); } [Fact] public void CS0409ERR_DuplicateConstraintClause() { var source = @"interface I<T> where T : class where T : struct { void M<U, V>() where U : new() where V : class where U : class where U : I<T>; }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "T").WithArguments("T").WithLocation(3, 11), // (8,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 15), // (9,15): error CS0409: A constraint clause has already been specified for type parameter 'T'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(9, 15)); } [Fact] public void CS0415ERR_BadIndexerNameAttr() { var text = @"using System; using System.Runtime.CompilerServices; public interface IA { int this[int index] { get; set; } } public class A : IA { [IndexerName(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } [IndexerName(""Item"")] // CS0415 int P { get; set; } [IndexerName(""Item"")] // CS0592 int f; [IndexerName(""Item"")] // CS0592 void M() { } [IndexerName(""Item"")] // CS0592 event Action E; [IndexerName(""Item"")] // CS0592 class C { } [IndexerName(""Item"")] // CS0592 struct S { } [IndexerName(""Item"")] // CS0592 delegate void D(); } "; CreateCompilation(text).VerifyDiagnostics( // (15,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (22,6): error CS0415: The 'IndexerName' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, "IndexerName").WithArguments("IndexerName"), // (26,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (29,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (32,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (35,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (38,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (41,6): error CS0592: Attribute 'IndexerName' is not valid on this declaration type. It is only valid on 'property, indexer' declarations. Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "IndexerName").WithArguments("IndexerName", "property, indexer"), // (27,9): warning CS0169: The field 'A.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("A.f"), // (33,18): warning CS0067: The event 'A.E' is never used Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("A.E")); } [Fact] public void CS0415ERR_BadIndexerNameAttr_Alias() { var text = @" using Alias = System.Runtime.CompilerServices.IndexerNameAttribute; public interface IA { int this[int index] { get; set; } } public class A : IA { [ Alias(""Item"")] // CS0415 int IA.this[int index] { get { return 0; } set { } } } "; var compilation = CreateCompilation(text); // NOTE: uses attribute name from syntax. compilation.VerifyDiagnostics( // (11,6): error CS0415: The 'Alias' attribute is valid only on an indexer that is not an explicit interface member declaration Diagnostic(ErrorCode.ERR_BadIndexerNameAttr, @"Alias").WithArguments("Alias")); // Note: invalid attribute had no effect on metadata name. var indexer = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("A").GetProperty("IA." + WellKnownMemberNames.Indexer); Assert.Equal("IA.Item", indexer.MetadataName); } [Fact] public void CS0416ERR_AttrArgWithTypeVars() { var text = @"public class MyAttribute : System.Attribute { public MyAttribute(System.Type t) { } } class G<T> { [MyAttribute(typeof(G<T>))] // CS0416 public void F() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttrArgWithTypeVars, Line = 10, Column = 18 }); } [Fact] public void CS0418ERR_AbstractSealedStatic01() { var text = @"namespace NS { public abstract static class C // CS0418 { internal abstract sealed class CC { private static abstract sealed class CCC // CS0418, 0441 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 3, Column = 34 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 5, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractSealedStatic, Line = 7, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SealedStaticClass, Line = 7, Column = 50 }); } [Fact] public void CS0423ERR_ComImportWithImpl() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class ImageProperties { public static void Main() // CS0423 { ImageProperties i = new ImageProperties(); } } "; CreateCompilation(text).VerifyDiagnostics( // (5,24): error CS0423: Since 'ImageProperties' has the ComImport attribute, 'ImageProperties.Main()' must be extern or abstract // public static void Main() // CS0423 Diagnostic(ErrorCode.ERR_ComImportWithImpl, "Main").WithArguments("ImageProperties.Main()", "ImageProperties").WithLocation(5, 24)); } [Fact] public void CS0424ERR_ComImportWithBase() { var text = @"using System.Runtime.InteropServices; public class A { } [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B : A { } // CS0424 error "; CreateCompilation(text).VerifyDiagnostics( // (5,7): error CS0424: 'B': a class with the ComImport attribute cannot specify a base class // class B : A { } // CS0424 error Diagnostic(ErrorCode.ERR_ComImportWithBase, "B").WithArguments("B").WithLocation(5, 7)); } [WorkItem(856187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/856187")] [WorkItem(866093, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/866093")] [Fact] public void CS0424ERR_ComImportWithInitializers() { var text = @" using System.Runtime.InteropServices; [ComImport, Guid(""7ab770c7-0e23-4d7a-8aa2-19bfad479829"")] class B { public static int X = 5; public int Y = 5; public const decimal D = 5; public const int Yconst = 5; } "; CreateCompilation(text).VerifyDiagnostics( // (7,25): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public static int X = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(7, 25), // (9,28): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public const decimal D = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(9, 28), // (8,18): error CS8028: 'B': a class with the ComImport attribute cannot specify field initializers. // public int Y = 5; Diagnostic(ErrorCode.ERR_ComImportWithInitializers, "= 5").WithArguments("B").WithLocation(8, 18) ); } [Fact] public void CS0425ERR_ImplBadConstraints01() { var source = @"interface IA<T> { } interface IB { } interface I { // Different constraints: void A1<T>() where T : struct; void A2<T, U>() where T : struct where U : IA<T>; void A3<T>() where T : IA<T>; void A4<T, U>() where T : struct, IA<T>; // Additional constraints: void B1<T>(); void B2<T>() where T : new(); void B3<T, U>() where T : IA<T>; // Missing constraints. void C1<T>() where T : class; void C2<T>() where T : class, new(); void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. void D1<T>() where T : IA<T>, IB; void D2<T, U, V>() where V : T, U; // Different constraint clauses. void E1<T, U>() where U : T; // Additional constraint clause. void F1<T, U>() where T : class; // Missing constraint clause. void G1<T, U>() where T : class where U : T; // Same constraint clauses, different order. void H1<T, U>() where T : class where U : T; void H2<T, U>() where T : class where U : T; void H3<T, U, V>() where V : class where U : IB where T : IA<V>; // Different type parameter names. void K1<T, U>() where T : class where U : T; void K2<T, U>() where T : class where U : T; } class C : I { // Different constraints: public void A1<T>() where T : class { } public void A2<T, U>() where T : struct where U : IB { } public void A3<T>() where T : IA<IA<T>> { } public void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: public void B1<T>() where T : new() { } public void B2<T>() where T : class, new() { } public void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. public void C1<T>() { } public void C2<T>() where T : class { } public void C3<T, U>() where U : IA<T> { } // Same constraints, different order. public void D1<T>() where T : IB, IA<T> { } public void D2<T, U, V>() where V : U, T { } // Different constraint clauses. public void E1<T, U>() where T : class { } // Additional constraint clause. public void F1<T, U>() where T : class where U : T { } // Missing constraint clause. public void G1<T, U>() where T : class { } // Same constraint clauses, different order. public void H1<T, U>() where U : T where T : class { } public void H2<T, U>() where U : class where T : U { } public void H3<T, U, V>() where T : IA<V> where U : IB where V : class { } // Different type parameter names. public void K1<U, T>() where T : class where U : T { } public void K2<T1, T2>() where T1 : class where T2 : T1 { } }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilation(source).VerifyDiagnostics( // (38,17): error CS0425: The constraints for type parameter 'T' of method 'C.A1<T>()' must match the constraints for type parameter 'T' of interface method 'I.A1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A1").WithArguments("T", "C.A1<T>()", "T", "I.A1<T>()").WithLocation(38, 17), // (39,17): error CS0425: The constraints for type parameter 'U' of method 'C.A2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.A2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A2").WithArguments("U", "C.A2<T, U>()", "U", "I.A2<T, U>()").WithLocation(39, 17), // (40,17): error CS0425: The constraints for type parameter 'T' of method 'C.A3<T>()' must match the constraints for type parameter 'T' of interface method 'I.A3<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A3").WithArguments("T", "C.A3<T>()", "T", "I.A3<T>()").WithLocation(40, 17), // (41,17): error CS0425: The constraints for type parameter 'T' of method 'C.A4<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.A4<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "A4").WithArguments("T", "C.A4<T, U>()", "T", "I.A4<T, U>()").WithLocation(41, 17), // (43,17): error CS0425: The constraints for type parameter 'T' of method 'C.B1<T>()' must match the constraints for type parameter 'T' of interface method 'I.B1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B1").WithArguments("T", "C.B1<T>()", "T", "I.B1<T>()").WithLocation(43, 17), // (44,17): error CS0425: The constraints for type parameter 'T' of method 'C.B2<T>()' must match the constraints for type parameter 'T' of interface method 'I.B2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B2").WithArguments("T", "C.B2<T>()", "T", "I.B2<T>()").WithLocation(44, 17), // (45,17): error CS0425: The constraints for type parameter 'T' of method 'C.B3<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.B3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "B3").WithArguments("T", "C.B3<T, U>()", "T", "I.B3<T, U>()").WithLocation(45, 17), // (47,17): error CS0425: The constraints for type parameter 'T' of method 'C.C1<T>()' must match the constraints for type parameter 'T' of interface method 'I.C1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C1").WithArguments("T", "C.C1<T>()", "T", "I.C1<T>()").WithLocation(47, 17), // (48,17): error CS0425: The constraints for type parameter 'T' of method 'C.C2<T>()' must match the constraints for type parameter 'T' of interface method 'I.C2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C2").WithArguments("T", "C.C2<T>()", "T", "I.C2<T>()").WithLocation(48, 17), // (49,17): error CS0425: The constraints for type parameter 'U' of method 'C.C3<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.C3<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "C3").WithArguments("U", "C.C3<T, U>()", "U", "I.C3<T, U>()").WithLocation(49, 17), // (54,17): error CS0425: The constraints for type parameter 'T' of method 'C.E1<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("T", "C.E1<T, U>()", "T", "I.E1<T, U>()").WithLocation(54, 17), // (54,17): error CS0425: The constraints for type parameter 'U' of method 'C.E1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.E1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "E1").WithArguments("U", "C.E1<T, U>()", "U", "I.E1<T, U>()").WithLocation(54, 17), // (56,17): error CS0425: The constraints for type parameter 'U' of method 'C.F1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.F1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "F1").WithArguments("U", "C.F1<T, U>()", "U", "I.F1<T, U>()").WithLocation(56, 17), // (58,17): error CS0425: The constraints for type parameter 'U' of method 'C.G1<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.G1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "G1").WithArguments("U", "C.G1<T, U>()", "U", "I.G1<T, U>()").WithLocation(58, 17), // (61,17): error CS0425: The constraints for type parameter 'T' of method 'C.H2<T, U>()' must match the constraints for type parameter 'T' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("T", "C.H2<T, U>()", "T", "I.H2<T, U>()").WithLocation(61, 17), // (61,17): error CS0425: The constraints for type parameter 'U' of method 'C.H2<T, U>()' must match the constraints for type parameter 'U' of interface method 'I.H2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "H2").WithArguments("U", "C.H2<T, U>()", "U", "I.H2<T, U>()").WithLocation(61, 17), // (64,17): error CS0425: The constraints for type parameter 'U' of method 'C.K1<U, T>()' must match the constraints for type parameter 'T' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("U", "C.K1<U, T>()", "T", "I.K1<T, U>()").WithLocation(64, 17), // (64,17): error CS0425: The constraints for type parameter 'T' of method 'C.K1<U, T>()' must match the constraints for type parameter 'U' of interface method 'I.K1<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "K1").WithArguments("T", "C.K1<U, T>()", "U", "I.K1<T, U>()").WithLocation(64, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints02() { var source = @"interface IA<T> { } interface IB { } interface I<T> { void M1<U, V>() where U : T where V : IA<T>; void M2<U>() where U : T, new(); } class C1 : I<IB> { public void M1<U, V>() where U : IB where V : IA<IB> { } public void M2<U>() where U : I<IB> { } } class C2<T, U> : I<IA<U>> { public void M1<X, Y>() where Y : IA<IA<U>> where X : IA<U> { } public void M2<X>() where X : T, new() { } }"; CreateCompilation(source).VerifyDiagnostics( // (11,17): error CS0425: The constraints for type parameter 'U' of method 'C1.M2<U>()' must match the constraints for type parameter 'U' of interface method 'I<IB>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("U", "C1.M2<U>()", "U", "I<IB>.M2<U>()").WithLocation(11, 17), // (16,17): error CS0425: The constraints for type parameter 'X' of method 'C2<T, U>.M2<X>()' must match the constraints for type parameter 'U' of interface method 'I<IA<U>>.M2<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("X", "C2<T, U>.M2<X>()", "U", "I<IA<U>>.M2<U>()").WithLocation(16, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints03() { var source = @"interface IA { } class B { } interface I1<T> { void M<U>() where U : struct, T; } class C1<T> : I1<T> where T : struct { public void M<U>() where U : T { } } interface I2<T> { void M<U>() where U : class, T; } class C2 : I2<B> { public void M<U>() where U : B { } } class C2<T> : I2<T> where T : class { public void M<U>() where U : T { } } interface I3<T> { void M<U>() where U : T, new(); } class C3 : I3<B> { public void M<U>() where U : B { } } class C3<T> : I3<T> where T : new() { public void M<U>() where U : T { } } interface I4<T> { void M<U>() where U : T, IA; } class C4 : I4<IA> { public void M<U>() where U : IA { } } class C4<T> : I4<T> where T : IA { public void M<U>() where U : T { } } interface I5<T> { void M<U>() where U : B, T; } class C5 : I5<B> { public void M<U>() where U : B { } } class C5<T> : I5<T> where T : B { public void M<U>() where U : T { } }"; CreateCompilation(source).VerifyDiagnostics( // (9,17): error CS0425: The constraints for type parameter 'U' of method 'C1<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I1<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C1<T>.M<U>()", "U", "I1<T>.M<U>()").WithLocation(9, 17), // (9,19): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 19), // (17,17): error CS0425: The constraints for type parameter 'U' of method 'C2.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2.M<U>()", "U", "I2<B>.M<U>()").WithLocation(17, 17), // (21,17): error CS0425: The constraints for type parameter 'U' of method 'C2<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I2<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C2<T>.M<U>()", "U", "I2<T>.M<U>()").WithLocation(21, 17), // (29,17): error CS0425: The constraints for type parameter 'U' of method 'C3.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<B>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3.M<U>()", "U", "I3<B>.M<U>()").WithLocation(29, 17), // (33,17): error CS0425: The constraints for type parameter 'U' of method 'C3<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I3<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C3<T>.M<U>()", "U", "I3<T>.M<U>()").WithLocation(33, 17), // (45,17): error CS0425: The constraints for type parameter 'U' of method 'C4<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I4<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C4<T>.M<U>()", "U", "I4<T>.M<U>()").WithLocation(45, 17), // (57,17): error CS0425: The constraints for type parameter 'U' of method 'C5<T>.M<U>()' must match the constraints for type parameter 'U' of interface method 'I5<T>.M<U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M").WithArguments("U", "C5<T>.M<U>()", "U", "I5<T>.M<U>()").WithLocation(57, 17)); } [Fact] public void CS0425ERR_ImplBadConstraints04() { var source = @"interface IA { void M1<T>(); void M2<T, U>() where U : T; } interface IB { void M1<T>() where T : IB; void M2<X, Y>(); } abstract class C : IA, IB { public abstract void M1<T>(); public abstract void M2<X, Y>(); }"; CreateCompilation(source).VerifyDiagnostics( // (14,26): error CS0425: The constraints for type parameter 'Y' of method 'C.M2<X, Y>()' must match the constraints for type parameter 'U' of interface method 'IA.M2<T, U>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("Y", "C.M2<X, Y>()", "U", "IA.M2<T, U>()").WithLocation(14, 26), // (13,26): error CS0425: The constraints for type parameter 'T' of method 'C.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "C.M1<T>()", "T", "IB.M1<T>()").WithLocation(13, 26)); } [Fact] public void CS0425ERR_ImplBadConstraints05() { var source = @"interface I<T> { } class C { } interface IA<T, U> { void A1<V>() where V : T, I<T>; void A2<V>() where V : T, U, I<T>, I<U>; } interface IB<T> { void B1<U>() where U : C; void B2<U, V>() where U : C, T, V; } class A<T, U> { // More constraints than IA<T, U>.A1<V>(). public void A1<V>() where V : T, U, I<T>, I<U> { } // Fewer constraints than IA<T, U>.A2<V>(). public void A2<V>() where V : T, I<T> { } } class B<T> { // More constraints than IB<T>.B1<U>(). public void B1<U>() where U : C, T { } // Fewer constraints than IB<T>.B2<U, V>(). public void B2<U, V>() where U : T, V { } } class A1<T> : A<T, T>, IA<T, T> { } class A2<T, U> : A<T, U>, IA<T, U> { } class B1 : B<C>, IB<C> { } class B2<T> : B<T>, IB<T> { }"; CreateCompilation(source).VerifyDiagnostics( // (30,27): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A2<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A2<V>()'. Consider using an explicit interface implementation instead. // class A2<T, U> : A<T, U>, IA<T, U> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IA<T, U>").WithArguments("V", "A<T, U>.A2<V>()", "V", "IA<T, U>.A2<V>()").WithLocation(30, 27), // (30,27): error CS0425: The constraints for type parameter 'V' of method 'A<T, U>.A1<V>()' must match the constraints for type parameter 'V' of interface method 'IA<T, U>.A1<V>()'. Consider using an explicit interface implementation instead. // class A2<T, U> : A<T, U>, IA<T, U> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IA<T, U>").WithArguments("V", "A<T, U>.A1<V>()", "V", "IA<T, U>.A1<V>()").WithLocation(30, 27), // (36,21): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B2<U, V>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B2<U, V>()'. Consider using an explicit interface implementation instead. // class B2<T> : B<T>, IB<T> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IB<T>").WithArguments("U", "B<T>.B2<U, V>()", "U", "IB<T>.B2<U, V>()").WithLocation(36, 21), // (36,21): error CS0425: The constraints for type parameter 'U' of method 'B<T>.B1<U>()' must match the constraints for type parameter 'U' of interface method 'IB<T>.B1<U>()'. Consider using an explicit interface implementation instead. // class B2<T> : B<T>, IB<T> Diagnostic(ErrorCode.ERR_ImplBadConstraints, "IB<T>").WithArguments("U", "B<T>.B1<U>()", "U", "IB<T>.B1<U>()").WithLocation(36, 21)); } [Fact] public void CS0425ERR_ImplBadConstraints06() { var source = @"using NIA1 = N.IA; using NIA2 = N.IA; using NA1 = N.A; using NA2 = N.A; namespace N { interface IA { } class A { } } interface IB { void M1<T>() where T : N.A, N.IA; void M2<T>() where T : NA1, NIA1; } abstract class B1 : IB { public abstract void M1<T>() where T : NA1, NIA1; public abstract void M2<T>() where T : NA2, NIA2; } abstract class B2 : IB { public abstract void M1<T>() where T : NA1; public abstract void M2<T>() where T : NIA2; }"; CreateCompilation(source).VerifyDiagnostics( // (22,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M1<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M1<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M1").WithArguments("T", "B2.M1<T>()", "T", "IB.M1<T>()").WithLocation(22, 26), // (23,26): error CS0425: The constraints for type parameter 'T' of method 'B2.M2<T>()' must match the constraints for type parameter 'T' of interface method 'IB.M2<T>()'. Consider using an explicit interface implementation instead. Diagnostic(ErrorCode.ERR_ImplBadConstraints, "M2").WithArguments("T", "B2.M2<T>()", "T", "IB.M2<T>()").WithLocation(23, 26)); } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg01() { var text = @"namespace NS { public class C { public interface I { } } struct S { } public class Test { C.I.x field; // CS0426 void M(S.s p) { } // CS0426 public static int Main() { // C.A a; // CS0426 return 1; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,18): error CS0426: The type name 's' does not exist in the type 'NS.S' // void M(S.s p) { } // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "s").WithArguments("s", "NS.S"), // (13,13): error CS0426: The type name 'x' does not exist in the type 'NS.C.I' // C.I.x field; // CS0426 Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "x").WithArguments("x", "NS.C.I"), // (13,15): warning CS0169: The field 'NS.Test.field' is never used // C.I.x field; // CS0426 Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Test.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0426ERR_DottedTypeNameNotFoundInAgg02() { var text = @"class A<T> { A<T>.T F = default(A<T>.T); } class B : A<object> { B.T F = default(B.T); }"; CreateCompilation(text).VerifyDiagnostics( // (3,10): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 10), // (3,29): error CS0426: The type name 'T' does not exist in the type 'A<T>' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "A<T>").WithLocation(3, 29), // (7,7): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 7), // (7,23): error CS0426: The type name 'T' does not exist in the type 'B' Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInAgg, "T").WithArguments("T", "B").WithLocation(7, 23)); } [Fact] public void CS0430ERR_BadExternAlias() { var text = @"extern alias MyType; // CS0430 public class Test { public static void Main() {} } public class MyClass { } "; CreateCompilation(text).VerifyDiagnostics( // (1,14): error CS0430: The extern alias 'MyType' was not specified in a /reference option // extern alias MyType; // CS0430 Diagnostic(ErrorCode.ERR_BadExternAlias, "MyType").WithArguments("MyType"), // (1,1): info CS8020: Unused extern alias. // extern alias MyType; // CS0430 Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias MyType;")); } [Fact] public void CS0432ERR_AliasNotFound() { var text = @"class C { public class A { } } class E : C::A { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AliasNotFound, Line = 6, Column = 11 }); } /// <summary> /// Import - same name class from lib1 and lib2 /// </summary> [Fact] public void CS0433ERR_SameFullNameAggAgg01() { var text = @"namespace NS { class Test { Class1 var; void M(Class1 p) {} } } "; var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var ref2 = TestReferences.SymbolsTests.MultiModule.Assembly; // Roslyn give CS0104 for now var comp = CreateCompilation(text, new List<MetadataReference> { ref1, ref2 }); comp.VerifyDiagnostics( // (6,16): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // void M(Class1 p) {} Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,9): error CS0433: The type 'Class1' exists in both 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' // Class1 var; Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "Class1").WithArguments("MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1", "MultiModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (5,16): warning CS0169: The field 'NS.Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("NS.Test.var")); text = @" class Class1 { } class Test { Class1 var; } "; comp = CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // goo.cs(8,5): warning CS0436: The type 'Class1' in 'goo.cs' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'goo.cs'. // Class1 var; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("goo.cs", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // goo.cs(8,12): warning CS0169: The field 'Test.var' is never used // Class1 var; Diagnostic(ErrorCode.WRN_UnreferencedField, "var").WithArguments("Test.var") ); } /// <summary> /// import - lib1: namespace A { namespace B { .class C {}.. }} /// vs. lib2: Namespace A { class B { class C{} } }} - use C /// </summary> [Fact] public void CS0434ERR_SameFullNameNsAgg01() { var text = @" namespace NS { public class Test { public static void Main() { // var v = new N1.N2.A(); } void M(N1.N2.A p) { } } } "; var ref1 = TestReferences.DiagnosticTests.ErrTestLib11.dll; var ref2 = TestReferences.DiagnosticTests.ErrTestLib02.dll; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { ref1, ref2 }, // new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 9, Column = 28 }, // Dev10 one error new ErrorDescription { Code = (int)ErrorCode.ERR_SameFullNameNsAgg, Line = 12, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs01() // I (Neal Gafter) was not able to reproduce this in Dev10 using the batch compiler, but the Dev10 // background compiler will emit this diagnostic (along with one other) for this code: // namespace NS { // namespace A { } // public class A { } // } // class B : NS.A { } //Compiling the scenario below using the native compiler gives CS0438 for me (Ed). { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0438 } } class Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0438 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs03() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs04() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs05() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [Fact()] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0438ERR_SameFullNameThisAggThisNs06() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // Test.cs(9,38): error CS0438: The type 'NS.Util' in 'Test.cs' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("Test.cs", "NS.Util", "ErrTestMod02.netmodule", "NS.Util") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0436WRN_SameFullNameThisAggAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0436: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util")); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0436WRN_SameFullNameThisAggAgg_02() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,43): warning CS0436: The type 'NS.Util.A' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util.A' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "A").WithArguments("ErrTestMod02.netmodule", "NS.Util.A", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util.A") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0435WRN_SameFullNameThisNsAgg_01() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod02.netmodule").VerifyDiagnostics( // (9,38): warning CS0435: The namespace 'NS.Util' in 'ErrTestMod02.netmodule' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'ErrTestMod02.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("ErrTestMod02.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(568953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568953")] public void CS0437WRN_SameFullNameThisAggNs_01() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A).Module); } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "ErrTestMod01.netmodule").VerifyDiagnostics( // (9,38): warning CS0437: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the imported namespace 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'ErrTestMod01.netmodule'. // Console.WriteLine(typeof(Util.A).Module); Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_01() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_02() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_03() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }); comp.VerifyDiagnostics( // (15,15): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_04() { var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); } } namespace Util { class A<T> {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), }); CompileAndVerify(comp).VerifyDiagnostics(); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_05() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_06() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_07() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_08() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } class Util {} } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,11): error CS0101: The namespace 'NS' already contains a definition for 'Util' // class Util {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_09() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_10() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_11() { var libSource = @" namespace NS { namespace Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_12() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_13() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), new CSharpCompilationReference(lib) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }, sourceFileName: "Test.cs"); comp.VerifyDiagnostics( // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util"), // Test.cs(9,38): warning CS0435: The namespace 'NS.Util' in 'Test.cs' conflicts with the imported type 'NS.Util' in 'Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'Test.cs'. // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "Util").WithArguments("Test.cs", "NS.Util", "Lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_14() { var libSource = @" namespace NS { public class Util { public class A {} } } "; var lib = CreateCompilation(libSource, assemblyName: "Lib", options: TestOptions.ReleaseDll); CompileAndVerify(lib); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } namespace Util { public class A {} } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), new CSharpCompilationReference(lib) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), MetadataReference.CreateFromImage(lib.EmitToArray()) }); comp.VerifyDiagnostics( // (13,15): error CS0101: The namespace 'NS' already contains a definition for 'Util' // namespace Util Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "Util").WithArguments("Util", "NS"), // (15,22): error CS0101: The namespace 'NS.Util' already contains a definition for 'A' // public class A {} Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "A").WithArguments("A", "NS.Util") ); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_15() { var mod3Source = @" namespace NS { namespace Util { public class A {} } } "; var mod3Ref = CreateCompilation(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), mod3Ref, s_mod1.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS.Util' already contains a definition for 'A' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("A", "NS.Util"), // (9,38): error CS0438: The type 'NS.Util' in 'ErrTestMod01.netmodule' conflicts with the namespace 'NS.Util' in 'ErrTestMod02.netmodule' // Console.WriteLine(typeof(Util.A)); // CS0101 Diagnostic(ErrorCode.ERR_SameFullNameThisAggThisNs, "Util").WithArguments("ErrTestMod01.netmodule", "NS.Util", "ErrTestMod02.netmodule", "NS.Util")); } [Fact()] [WorkItem(530676, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530676")] public void CS0101ERR_DuplicateNameInNS_16() { var mod3Source = @" namespace NS { internal class Util { public class A {} } }"; var mod3Ref = CreateCompilation(mod3Source, options: TestOptions.ReleaseModule, assemblyName: "ErrTestMod03").EmitToImageReference(); var text = @"using System; namespace NS { public class Test { public static void Main() { Console.WriteLine(typeof(Util.A)); // CS0101 } } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), s_mod2.GetReference(), mod3Ref }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod2.GetReference(), s_mod1.GetReference(), mod3Ref }); //ErrTestMod01.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod02.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); comp = CreateCompilation(text, new List<MetadataReference>() { s_mod1.GetReference(), mod3Ref, s_mod2.GetReference() }); //ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' //ErrTestMod01.netmodule: (Location of symbol related to previous error) comp.VerifyDiagnostics( // ErrTestMod03.netmodule: error CS0101: The namespace 'NS' already contains a definition for 'Util' Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("Util", "NS")); } [ConditionalFact(typeof(DesktopOnly), typeof(ClrOnly))] [WorkItem(641639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/641639")] public void Bug641639() { var ModuleA01 = @" class A01 { public static int AT = (new { field = 1 }).field; } "; var ModuleA01Ref = CreateCompilation(ModuleA01, options: TestOptions.ReleaseModule, assemblyName: "ModuleA01").EmitToImageReference(); var ModuleB01 = @" class B01{ public static int AT = (new { field = 2 }).field; } "; var ModuleB01Ref = CreateCompilation(ModuleB01, options: TestOptions.ReleaseModule, assemblyName: "ModuleB01").EmitToImageReference(); var text = @" class Test { static void Main() { System.Console.WriteLine(""{0} + {1} = {2}"", A01.AT, A01.AT, B01.AT); A01.AT = B01.AT; System.Console.WriteLine(""{0} = {1}"", A01.AT, B01.AT); } } "; var comp = CreateCompilation(text, new List<MetadataReference>() { ModuleA01Ref, ModuleB01Ref }, TestOptions.ReleaseExe); Assert.Equal(1, comp.Assembly.Modules[1].GlobalNamespace.GetTypeMembers("<ModuleA01>f__AnonymousType0", 1).Length); Assert.Equal(1, comp.Assembly.Modules[2].GlobalNamespace.GetTypeMembers("<ModuleB01>f__AnonymousType0", 1).Length); CompileAndVerify(comp, expectedOutput: @"1 + 1 = 2 2 = 2"); } [Fact] public void NameCollisionWithAddedModule_01() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module ITest20Mod.netmodule // MVID: {53AFCDC2-985A-43AE-928E-89B4A4017344} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00EC0000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ITest20<T> { } // end of class ITest20 "; ImmutableArray<Byte> ilBytes; using (var reference = IlasmUtilities.CreateTempAssembly(ilSource, prependDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var source = @" interface ITest20 {} "; var compilation = CreateCompilation(source, new List<MetadataReference>() { moduleRef }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8004: Type 'ITest20<T>' exported from module 'ITest20Mod.netmodule' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ExportedTypeConflictsWithDeclaration).WithArguments("ITest20<T>", "ITest20Mod.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_02() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .module mod_1_1.netmodule // MVID: {98479031-F5D1-443D-AF73-CF21159C1BCF} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00D30000 // =============== CLASS MEMBERS DECLARATION =================== .class interface public abstract auto ansi ns.c1<T> { } .class interface public abstract auto ansi c2<T> { } .class interface public abstract auto ansi ns.C3<T> { } .class interface public abstract auto ansi C4<T> { } .class interface public abstract auto ansi NS1.c5<T> { } "; ImmutableArray<Byte> ilBytes; using (var reference = IlasmUtilities.CreateTempAssembly(ilSource, prependDefaultHeader: false)) { ilBytes = ReadFromFile(reference.Path); } var moduleRef1 = ModuleMetadata.CreateFromImage(ilBytes).GetReference(); var mod2Source = @" namespace ns { public interface c1 {} public interface c3 {} } public interface c2 {} public interface c4 {} namespace ns1 { public interface c5 {} } "; var moduleRef2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "mod_1_2").EmitToImageReference(); var compilation = CreateCompilation("", new List<MetadataReference>() { moduleRef1, moduleRef2 }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8005: Type 'c2' exported from module 'mod_1_2.netmodule' conflicts with type 'c2<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("c2", "mod_1_2.netmodule", "c2<T>", "mod_1_1.netmodule"), // error CS8005: Type 'ns.c1' exported from module 'mod_1_2.netmodule' conflicts with type 'ns.c1<T>' exported from module 'mod_1_1.netmodule'. Diagnostic(ErrorCode.ERR_ExportedTypesConflict).WithArguments("ns.c1", "mod_1_2.netmodule", "ns.c1<T>", "mod_1_1.netmodule") ); } [Fact] public void NameCollisionWithAddedModule_03() { var forwardedTypesSource = @" public class CF1 {} namespace ns { public class CF2 { } } public class CF3<T> {} "; var forwardedTypes1 = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes1"); var forwardedTypes1Ref = new CSharpCompilationReference(forwardedTypes1); var forwardedTypes2 = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseDll, assemblyName: "ForwardedTypes2"); var forwardedTypes2Ref = new CSharpCompilationReference(forwardedTypes2); var forwardedTypesModRef = CreateCompilation(forwardedTypesSource, options: TestOptions.ReleaseModule, assemblyName: "forwardedTypesMod"). EmitToImageReference(); var modSource = @" [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(ns.CF2))] "; var module1_FT1_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module1_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module2_FT1_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module2_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var module3_FT2_Ref = CreateCompilation(modSource, options: TestOptions.ReleaseModule, assemblyName: "module3_FT2", references: new MetadataReference[] { forwardedTypes2Ref }). EmitToImageReference(); var module4_Ref = CreateCompilation("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<int>))]", options: TestOptions.ReleaseModule, assemblyName: "module4_FT1", references: new MetadataReference[] { forwardedTypes1Ref }). EmitToImageReference(); var compilation = CreateCompilation(forwardedTypesSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8006: Forwarded type 'ns.CF2' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("ns.CF2"), // error CS8006: Forwarded type 'CF1' conflicts with type declared in primary module of this assembly. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithDeclaration).WithArguments("CF1")); compilation = CreateCompilation(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); // Exported types in .NET modules cause PEVerify to fail on some platforms. CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation("[assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(CF3<byte>))]", new List<MetadataReference>() { module4_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation(modSource, new List<MetadataReference>() { module1_FT1_Ref, forwardedTypes2Ref, new CSharpCompilationReference(forwardedTypes1, aliases: ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); compilation = CreateCompilation( @" extern alias FT1; [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::CF1))] [assembly: System.Runtime.CompilerServices.TypeForwardedToAttribute(typeof(FT1::ns.CF2))] ", new List<MetadataReference>() { forwardedTypesModRef, new CSharpCompilationReference(forwardedTypes1, ImmutableArray.Create("FT1")) }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule"), // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { forwardedTypesModRef, module1_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, forwardedTypesModRef, forwardedTypes1Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8008: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "forwardedTypesMod.netmodule"), // error CS8008: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' exported from module 'forwardedTypesMod.netmodule'. Diagnostic(ErrorCode.ERR_ForwardedTypeConflictsWithExportedType).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "forwardedTypesMod.netmodule")); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, module2_FT1_Ref, forwardedTypes1Ref }, TestOptions.ReleaseDll); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilation("", new List<MetadataReference>() { module1_FT1_Ref, module3_FT2_Ref, forwardedTypes1Ref, forwardedTypes2Ref }, TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics( // error CS8007: Type 'ns.CF2' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'ns.CF2' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("ns.CF2", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "ns.CF2", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // error CS8007: Type 'CF1' forwarded to assembly 'ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' conflicts with type 'CF1' forwarded to assembly 'ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_ForwardedTypesConflict).WithArguments("CF1", "ForwardedTypes1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CF1", "ForwardedTypes2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [Fact] public void CS0441ERR_SealedStaticClass01() { var text = @"namespace NS { static sealed class Test { public static int Main() { return 1; } } sealed static class StaticClass : Test //verify 'sealed' works { } static class Derived : StaticClass //verify 'sealed' works { // Test tst = new Test(); //verify 'static' works } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,25): error CS0441: 'NS.Test': a type cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "Test").WithArguments("NS.Test"), // (11,25): error CS0441: 'NS.StaticClass': a type cannot be both static and sealed Diagnostic(ErrorCode.ERR_SealedStaticClass, "StaticClass").WithArguments("NS.StaticClass"), //CONSIDER: Dev10 skips these cascading errors // (11,39): error CS07: Static class 'NS.StaticClass' cannot derive from type 'NS.Test'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Test").WithArguments("NS.StaticClass", "NS.Test"), // (15,28): error CS07: Static class 'NS.Derived' cannot derive from type 'NS.StaticClass'. Static classes must derive from object. Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "StaticClass").WithArguments("NS.Derived", "NS.StaticClass")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0442ERR_PrivateAbstractAccessor() { var source = @"abstract class MyClass { public abstract int P { get; private set; } // CS0442 protected abstract object Q { private get; set; } // CS0442 internal virtual object R { private get; set; } // no error } "; CreateCompilation(source).VerifyDiagnostics( // (3,42): error CS0442: 'MyClass.P.set': abstract properties cannot have private accessors // public abstract int P { get; private set; } // CS0442 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "set").WithArguments("MyClass.P.set").WithLocation(3, 42), // (4,43): error CS0442: 'MyClass.Q.get': abstract properties cannot have private accessors // protected abstract object Q { private get; set; } // CS0442 Diagnostic(ErrorCode.ERR_PrivateAbstractAccessor, "get").WithArguments("MyClass.Q.get").WithLocation(4, 43)); } [Fact] public void CS0448ERR_BadIncDecRetType() { // Note that the wording of this error message has changed slightly from the native compiler. var text = @"public struct S { public static S? operator ++(S s) { return new S(); } // CS0448 public static S? operator --(S s) { return new S(); } // CS0448 }"; CreateCompilation(text).VerifyDiagnostics( // (3,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator ++(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "++"), // (4,31): error CS0448: The return type for ++ or -- operator must match the parameter type or be derived from the parameter type // public static S? operator --(S s) { return new S(); } // CS0448 Diagnostic(ErrorCode.ERR_BadIncDecRetType, "--")); } [Fact] public void CS0450ERR_RefValBoundWithClass() { var source = @"interface I { } class A { } class B<T> { } class C<T1, T2, T3, T4, T5, T6, T7> where T1 : class, I where T2 : struct, I where T3 : class, A where T4 : struct, B<T5> where T6 : class, T5 where T7 : struct, T5 { }"; CreateCompilation(source).VerifyDiagnostics( // (7,23): error CS0450: 'A': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "A").WithArguments("A").WithLocation(7, 23), // (8, 24): error CS0450: 'B<T5>': cannot specify both a constraint class and the 'class' or 'struct' constraint Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "B<T5>").WithArguments("B<T5>").WithLocation(8, 24)); } [Fact] public void CS0452ERR_RefConstraintNotSatisfied() { var source = @"interface I { } class A { } class B<T> where T : class { } class C { static void F<U>() where U : class { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>() Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (19,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(19, 15), // (20,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(20, 9), // (24,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (39,15): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0452: The type 'int?' must be a reference type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied01() { var source = @"interface I { } class A { } class B<T> where T : struct { } class C { static void F<U>() where U : struct { } static void M1<T>() { new B<T>(); F<T>(); } static void M2<T>() where T : class { new B<T>(); F<T>(); } static void M3<T>() where T : struct { new B<T>(); F<T>(); } static void M4<T>() where T : new() { new B<T>(); F<T>(); } static void M5<T>() where T : I { new B<T>(); F<T>(); } static void M6<T>() where T : A { new B<T>(); F<T>(); } static void M7<T, U>() where T : U { new B<T>(); F<T>(); } static void M8() { new B<int?>(); F<int?>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (9,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(9, 15), // (10,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(10, 9), // (14,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(14, 15), // (15,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(15, 9), // (24,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(24, 15), // (25,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(25, 9), // (29,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(29, 15), // (30,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(30, 9), // (34,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(34, 15), // (35,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(35, 9), // (39,15): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "T").WithArguments("B<T>", "T", "T").WithLocation(39, 15), // (40,9): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<T>").WithArguments("C.F<U>()", "U", "T").WithLocation(40, 9), // (44,15): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B<T>' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "int?").WithArguments("B<T>", "T", "int?").WithLocation(44, 15), // (45,9): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<int?>").WithArguments("C.F<U>()", "U", "int?").WithLocation(45, 9)); } [Fact] public void CS0453ERR_ValConstraintNotSatisfied02() { var source = @"abstract class A<X, Y> { internal static void F<U>() where U : struct { } internal abstract void M<U>() where U : X, Y; } class B1 : A<int?, object> { internal override void M<U>() { F<U>(); } } class B2 : A<object, int?> { internal override void M<U>() { F<U>(); } } class B3 : A<object, int> { internal override void M<U>() { F<U>(); } } class B4<T> : A<object, T> { internal override void M<U>() { F<U>(); } } class B5<T> : A<object, T> where T : struct { internal override void M<U>() { F<U>(); } }"; CreateCompilation(source).VerifyDiagnostics( // (10,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<int?, object>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<int?, object>.F<U>()", "U", "U").WithLocation(10, 9), // (17,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, int?>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, int?>.F<U>()", "U", "U").WithLocation(17, 9), // (31,9): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'A<object, T>.F<U>()' Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<U>").WithArguments("A<object, T>.F<U>()", "U", "U").WithLocation(31, 9)); } [Fact] public void CS0454ERR_CircularConstraint01() { var source = @"class A<T> where T : T { } class B<T, U, V> where V : T where U : V where T : U { } delegate void D<T1, T2, T3>() where T1 : T3 where T2 : T2 where T3 : T1;"; CreateCompilation(source).VerifyDiagnostics( // (1,9): error CS0454: Circular constraint dependency involving 'T' and 'T' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(1, 9), // (4,9): error CS0454: Circular constraint dependency involving 'T' and 'V' Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "V").WithLocation(4, 9), // (10,17): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(10, 17), // (10,21): error CS0454: Circular constraint dependency involving 'T2' and 'T2' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T2").WithLocation(10, 21)); } [Fact] public void CS0454ERR_CircularConstraint02() { var source = @"interface I { void M<T, U, V>() where T : V, new() where U : class, V where V : U; } class A<T> { } class B<T, U> where T : U where U : A<U>, U { }"; CreateCompilation(source).VerifyDiagnostics( // (3,18): error CS0454: Circular constraint dependency involving 'V' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "V").WithArguments("V", "U").WithLocation(3, 18), // (9,12): error CS0454: Circular constraint dependency involving 'U' and 'U' Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(9, 12)); } [Fact] public void CS0454ERR_CircularConstraint03() { var source = @"interface I<T1, T2, T3, T4, T5> where T1 : T2, T4 where T2 : T3 where T3 : T1 where T4 : T5 where T5 : T1 { } class C<T1, T2, T3, T4, T5> where T1 : T2, T3 where T2 : T3, T4 where T3 : T4, T5 where T5 : T2, T3 { } struct S<T1, T2, T3, T4, T5> where T4 : T1 where T5 : T2 where T1 : T3 where T2 : T4 where T3 : T5 { } delegate void D<T1, T2, T3, T4>() where T1 : T2 where T2 : T3, T4 where T3 : T4 where T4 : T2;"; CreateCompilation(source).VerifyDiagnostics( // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T3' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T3").WithLocation(1, 13), // (1,13): error CS0454: Circular constraint dependency involving 'T1' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T5").WithLocation(1, 13), // (9,13): error CS0454: Circular constraint dependency involving 'T2' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T5").WithLocation(9, 13), // (9,17): error CS0454: Circular constraint dependency involving 'T3' and 'T5' Diagnostic(ErrorCode.ERR_CircularConstraint, "T3").WithArguments("T3", "T5").WithLocation(9, 17), // (16,10): error CS0454: Circular constraint dependency involving 'T1' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T1").WithArguments("T1", "T4").WithLocation(16, 10), // (24,21): error CS0454: Circular constraint dependency involving 'T2' and 'T4' Diagnostic(ErrorCode.ERR_CircularConstraint, "T2").WithArguments("T2", "T4").WithLocation(24, 21)); } [Fact] public void CS0454ERR_CircularConstraint04() { var source = @"interface I<T> where U : U { } class C<T, U> where T : U where U : class where U : T { }"; CreateCompilation(source).VerifyDiagnostics( // (2,11): error CS0699: 'I<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "I<T>").WithLocation(2, 11), // (8,11): error CS0409: A constraint clause has already been specified for type parameter 'U'. All of the constraints for a type parameter must be specified in a single where clause. Diagnostic(ErrorCode.ERR_DuplicateConstraintClause, "U").WithArguments("U").WithLocation(8, 11)); } [Fact] public void CS0455ERR_BaseConstraintConflict01() { var source = @"class A<T> { } class B : A<int> { } class C<T, U> where T : B, U where U : A<int> { } class D<T, U> where T : A<T> where U : B, T { }"; CreateCompilation(source).VerifyDiagnostics( // (8,12): error CS0455: Type parameter 'U' inherits conflicting constraints 'A<T>' and 'B' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "A<T>", "B").WithLocation(8, 12)); } [Fact] public void CS0455ERR_BaseConstraintConflict02() { var source = @"class A<T> { internal virtual void M1<U>() where U : struct, T { } internal virtual void M2<U>() where U : class, T { } } class B1 : A<object> { internal override void M1<U>() { } internal override void M2<U>() { } } class B2 : A<int> { internal override void M1<U>() { } internal override void M2<U>() { } } class B3 : A<string> { internal override void M1<U>() { } internal override void M2<U>() { } } class B4 : A<int?> { internal override void M1<T>() { } internal override void M2<X>() { } }"; CreateCompilation(source).VerifyDiagnostics( // (14,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'int' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "int", "class").WithLocation(14, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'string' and 'System.ValueType' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "string", "System.ValueType").WithLocation(18, 31), // (18,31): error CS0455: Type parameter 'U' inherits conflicting constraints 'System.ValueType' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "U").WithArguments("U", "System.ValueType", "struct").WithLocation(18, 31), // (23,31): error CS0455: Type parameter 'T' inherits conflicting constraints 'int?' and 'struct' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "T").WithArguments("T", "int?", "struct").WithLocation(23, 31), // (24,31): error CS0455: Type parameter 'X' inherits conflicting constraints 'int?' and 'class' Diagnostic(ErrorCode.ERR_BaseConstraintConflict, "X").WithArguments("X", "int?", "class").WithLocation(24, 31)); } [Fact] public void CS0456ERR_ConWithValCon() { var source = @"class A<T, U> where T : struct where U : T { } class B<T> where T : struct { void M<U>() where U : T { } struct S<U> where U : T { } }"; CreateCompilation(source).VerifyDiagnostics( // (1,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(1, 12), // (8,12): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(8, 12), // (9,14): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(9, 14)); } [Fact] public void CS0462ERR_AmbigOverride() { var text = @"class C<T> { public virtual void F(T t) {} public virtual void F(int t) {} } class D : C<int> { public override void F(int t) {} // CS0462 } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation) { comp.VerifyDiagnostics( // (9,25): error CS0462: The inherited members 'C<T>.F(T)' and 'C<T>.F(int)' have the same signature in type 'D', so they cannot be overridden // public override void F(int t) {} // CS0462 Diagnostic(ErrorCode.ERR_AmbigOverride, "F").WithArguments("C<T>.F(T)", "C<T>.F(int)", "D").WithLocation(9, 25) ); } else { comp.VerifyDiagnostics( // (3,24): warning CS1957: Member 'D.F(int)' overrides 'C<int>.F(int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void F(T t) {} Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F").WithArguments("C<int>.F(int)", "D.F(int)").WithLocation(3, 24), // (9,25): error CS0462: The inherited members 'C<T>.F(T)' and 'C<T>.F(int)' have the same signature in type 'D', so they cannot be overridden // public override void F(int t) {} // CS0462 Diagnostic(ErrorCode.ERR_AmbigOverride, "F").WithArguments("C<T>.F(T)", "C<T>.F(int)", "D").WithLocation(9, 25) ); } } [Fact] public void CS0466ERR_ExplicitImplParams() { var text = @"interface I { void M1(params int[] a); void M2(int[] a); } class C1 : I { //implicit implementations can add or remove 'params' public virtual void M1(int[] a) { } public virtual void M2(params int[] a) { } } class C2 : I { //explicit implementations can remove but not add 'params' void I.M1(int[] a) { } void I.M2(params int[] a) { } //CS0466 } class C3 : C1 { //overrides can add or remove 'params' public override void M1(params int[] a) { } public override void M2(int[] a) { } } class C4 : C1 { //hiding methods can add or remove 'params' public new void M1(params int[] a) { } public new void M2(int[] a) { } } "; CreateCompilation(text).VerifyDiagnostics( // (18,12): error CS0466: 'C2.I.M2(params int[])' should not have a params parameter since 'I.M2(int[])' does not Diagnostic(ErrorCode.ERR_ExplicitImplParams, "M2").WithArguments("C2.I.M2(params int[])", "I.M2(int[])")); } [Fact] public void CS0470ERR_MethodImplementingAccessor() { var text = @"interface I { int P { get; } } class MyClass : I { public int get_P() { return 0; } // CS0470 public int P2 { get { return 0; } } // OK } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 17 }, //Dev10 doesn't include this new ErrorDescription { Code = (int)ErrorCode.ERR_MethodImplementingAccessor, Line = 8, Column = 16 }); } [Fact] public void CS0500ERR_AbstractHasBody01() { var text = @"namespace NS { abstract public class clx { abstract public void M1() { } internal abstract object M2() { return null; } protected abstract internal void M3(sbyte p) { } public abstract object P { get { return null; } set { } } public abstract event System.Action E { add { } remove { } } public abstract event System.Action X { add => throw null; remove => throw null; } } // class clx } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (5,30): error CS0500: 'clx.M1()' cannot declare a body because it is marked abstract // abstract public void M1() { } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M1").WithArguments("NS.clx.M1()").WithLocation(5, 30), // (6,34): error CS0500: 'clx.M2()' cannot declare a body because it is marked abstract // internal abstract object M2() { return null; } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M2").WithArguments("NS.clx.M2()").WithLocation(6, 34), // (7,42): error CS0500: 'clx.M3(sbyte)' cannot declare a body because it is marked abstract // protected abstract internal void M3(sbyte p) { } Diagnostic(ErrorCode.ERR_AbstractHasBody, "M3").WithArguments("NS.clx.M3(sbyte)").WithLocation(7, 42), // (8,36): error CS0500: 'clx.P.get' cannot declare a body because it is marked abstract // public abstract object P { get { return null; } set { } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "get").WithArguments("NS.clx.P.get").WithLocation(8, 36), // (8,57): error CS0500: 'clx.P.set' cannot declare a body because it is marked abstract // public abstract object P { get { return null; } set { } } Diagnostic(ErrorCode.ERR_AbstractHasBody, "set").WithArguments("NS.clx.P.set").WithLocation(8, 57), // (9,47): error CS8712: 'clx.E': abstract event cannot use event accessor syntax // public abstract event System.Action E { add { } remove { } } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("NS.clx.E").WithLocation(9, 47), // (10,47): error CS8712: 'clx.X': abstract event cannot use event accessor syntax // public abstract event System.Action X { add => throw null; remove => throw null; } Diagnostic(ErrorCode.ERR_AbstractEventHasAccessors, "{").WithArguments("NS.clx.X").WithLocation(10, 47)); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0501ERR_ConcreteMissingBody01() { var text = @" namespace NS { public class clx<T> { public void M1(T t); internal V M2<V>(); protected internal void M3(sbyte p); public static int operator+(clx<T> c); } // class clx } "; CreateCompilation(text).VerifyDiagnostics( // (7,21): error CS0501: 'NS.clx<T>.M1(T)' must declare a body because it is not marked abstract, extern, or partial // public void M1(T t); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M1").WithArguments("NS.clx<T>.M1(T)"), // (8,20): error CS0501: 'NS.clx<T>.M2<V>()' must declare a body because it is not marked abstract, extern, or partial // internal V M2<V>(); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M2").WithArguments("NS.clx<T>.M2<V>()"), // (9,33): error CS0501: 'NS.clx<T>.M3(sbyte)' must declare a body because it is not marked abstract, extern, or partial // protected internal void M3(sbyte p); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M3").WithArguments("NS.clx<T>.M3(sbyte)"), // (10,35): error CS0501: 'NS.clx<T>.operator +(NS.clx<T>)' must declare a body because it is not marked abstract, extern, or partial // public static int operator+(clx<T> c); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("NS.clx<T>.operator +(NS.clx<T>)")); } [Fact] public void CS0501ERR_ConcreteMissingBody02() { var text = @"abstract class C { public int P { get; set { } } public int Q { get { return 0; } set; } public extern object R { get; } // no error protected abstract object S { set; } // no error } "; CreateCompilation(text).VerifyDiagnostics( // (3,20): error CS0501: 'C.P.get' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "get").WithArguments("C.P.get"), // (4,38): error CS0501: 'C.Q.set' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("C.Q.set"), // (5,30): warning CS0626: Method, operator, or accessor 'C.R.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.R.get")); } [Fact] public void CS0501ERR_ConcreteMissingBody03() { var source = @"class C { public C(); internal abstract C(C c); extern public C(object o); // no error }"; CreateCompilation(source).VerifyDiagnostics( // (3,12): error CS0501: 'C.C()' must declare a body because it is not marked abstract, extern, or partial Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "C").WithArguments("C.C()"), // (4,23): error CS0106: The modifier 'abstract' is not valid for this item Diagnostic(ErrorCode.ERR_BadMemberFlag, "C").WithArguments("abstract"), // (5,19): warning CS0824: Constructor 'C.C(object)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("C.C(object)")); } [Fact] public void CS0502ERR_AbstractAndSealed01() { var text = @"namespace NS { abstract public class clx { abstract public void M1(); abstract protected void M2<T>(T t); internal abstract object P { get; } abstract public event System.Action E; } // class clx abstract public class cly : clx { abstract sealed override public void M1(); abstract sealed override protected void M2<T>(T t); internal abstract sealed override object P { get; } public abstract sealed override event System.Action E; } // class cly } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 13, Column = 46 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 14, Column = 49 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 15, Column = 50 }, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAndSealed, Line = 16, Column = 61 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0503ERR_AbstractNotVirtual01() { var source = @"namespace NS { abstract public class clx { abstract virtual internal void M1(); abstract virtual protected void M2<T>(T t); virtual abstract public object P { get; set; } virtual abstract public event System.Action E; } // class clx } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (7,40): error CS0503: The abstract property 'clx.P' cannot be marked virtual // virtual abstract public object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "P").WithArguments("property", "NS.clx.P").WithLocation(7, 40), // (6,41): error CS0503: The abstract method 'clx.M2<T>(T)' cannot be marked virtual // abstract virtual protected void M2<T>(T t); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M2").WithArguments("method", "NS.clx.M2<T>(T)").WithLocation(6, 41), // (5,40): error CS0503: The abstract method 'clx.M1()' cannot be marked virtual // abstract virtual internal void M1(); Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "M1").WithArguments("method", "NS.clx.M1()").WithLocation(5, 40), // (8,53): error CS0503: The abstract event 'clx.E' cannot be marked virtual // virtual abstract public event System.Action E; Diagnostic(ErrorCode.ERR_AbstractNotVirtual, "E").WithArguments("event", "NS.clx.E").WithLocation(8, 53)); var nsNamespace = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var clxClass = nsNamespace.GetMembers("clx").Single() as NamedTypeSymbol; Assert.Equal(9, clxClass.GetMembers().Length); } [Fact] public void CS0504ERR_StaticConstant() { var text = @"namespace x { abstract public class clx { static const int i = 0; // CS0504, cannot be both static and const abstract public void f(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstant, Line = 5, Column = 26 }); } [Fact] public void CS0505ERR_CantOverrideNonFunction() { var text = @"public class clx { public int i; } public class cly : clx { public override int i() { return 0; } // CS0505 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonFunction, Line = 8, Column = 24 }); } [Fact] public void CS0506ERR_CantOverrideNonVirtual() { var text = @"namespace MyNameSpace { abstract public class ClassX { public int f() { return 0; } } public class ClassY : ClassX { public override int f() // CS0506 { return 0; } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 13, Column = 29 }); } private const string s_typeWithMixedProperty = @" .class public auto ansi beforefieldinit Base_VirtGet_Set extends [mscorlib]System.Object { .method public hidebysig specialname newslot virtual instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_VirtGet_Set::get_Prop() .set instance void Base_VirtGet_Set::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } .class public auto ansi beforefieldinit Base_Get_VirtSet extends [mscorlib]System.Object { .method public hidebysig specialname instance int32 get_Prop() cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: ldc.i4.1 IL_0001: ret } .method public hidebysig specialname newslot virtual instance void set_Prop(int32 'value') cil managed { // Code size 1 (0x1) .maxstack 8 IL_0000: ret } .property instance int32 Prop() { .get instance int32 Base_Get_VirtSet::get_Prop() .set instance void Base_Get_VirtSet::set_Prop(int32) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } } "; [WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } set { base.Prop = value; } } } "; var comp = CreateCompilationWithILAndMscorlib40(text, s_typeWithMixedProperty); comp.VerifyDiagnostics( // (4,25): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // get { return base.Prop; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "get").WithArguments("Derived1.Prop.get", "Base_Get_VirtSet.Prop.get"), // (16,9): error CS0506: 'Derived2.Prop.set': cannot override inherited member 'Base_VirtGet_Set.Prop.set' because it is not marked virtual, abstract, or override // set { base.Prop = value; } Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "set").WithArguments("Derived2.Prop.set", "Base_VirtGet_Set.Prop.set")); } [WorkItem(543263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543263")] [Fact] public void CS0506ERR_CantOverrideNonVirtual_Imported_NO_ERROR() { var text = @" class Derived1 : Base_Get_VirtSet { public override int Prop { set { base.Prop = value; } } } class Derived2 : Base_VirtGet_Set { public override int Prop { get { return base.Prop; } } } "; var comp = CreateCompilationWithILAndMscorlib40(text, s_typeWithMixedProperty); comp.VerifyDiagnostics(); } [WorkItem(539586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539586")] [Fact] public void CS0506ERR_CantOverrideNonVirtual02() { var text = @"public class BaseClass { public virtual int Test() { return 1; } } public class BaseClass2 : BaseClass { public static int Test() // Warning CS0114 { return 1; } } public class MyClass : BaseClass2 { public override int Test() // Error CS0506 { return 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 11, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonVirtual, Line = 19, Column = 25 }); } [Fact] public void CS0507ERR_CantChangeAccessOnOverride() { var text = @"abstract public class clx { virtual protected void f() { } } public class cly : clx { public override void f() { } // CS0507 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeAccessOnOverride, Line = 8, Column = 26 }); } [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride() { var text = @"abstract public class Clx { public int i = 0; abstract public int F(); } public class Cly : Clx { public override double F() { return 0.0; // CS0508 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantChangeReturnTypeOnOverride, Line = 9, Column = 28 }); } [WorkItem(540325, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540325")] [Fact] public void CS0508ERR_CantChangeReturnTypeOnOverride2() { // When the overriding and overridden methods differ in their generic method // type parameter names, the error message should state what the return type // type should be on the overriding method using its type parameter names, // rather than using the return type of the overridden method. var text = @" class G { internal virtual T GM<T>(T t) { return t; } } class GG : G { internal override void GM<V>(V v) { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,24): error CS0508: 'GG.GM<V>(V)': return type must be 'V' to match overridden member 'G.GM<T>(T)' // internal override void GM<V>(V v) { } Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "GM").WithArguments("GG.GM<V>(V)", "G.GM<T>(T)", "V") ); } [Fact] public void CS0509ERR_CantDeriveFromSealedType01() { var source = @"namespace NS { public struct stx { } public sealed class clx {} public class cly : clx {} public class clz : stx { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,24): error CS0509: 'clz': cannot derive from sealed type 'stx' // public class clz : stx { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "stx").WithArguments("NS.clz", "NS.stx").WithLocation(7, 24), // (6,24): error CS0509: 'cly': cannot derive from sealed type 'clx' // public class cly : clx {} Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "clx").WithArguments("NS.cly", "NS.clx").WithLocation(6, 24)); } [Fact] public void CS0509ERR_CantDeriveFromSealedType02() { var source = @"namespace N1 { enum E { A, B } } namespace N2 { class C : N1.E { } class D : System.Int32 { } class E : int { } } "; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS0509: 'E': cannot derive from sealed type 'int' // class E : int { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "int").WithArguments("N2.E", "int").WithLocation(6, 15), // (4,15): error CS0509: 'C': cannot derive from sealed type 'E' // class C : N1.E { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "N1.E").WithArguments("N2.C", "N1.E").WithLocation(4, 15), // (5,15): error CS0509: 'D': cannot derive from sealed type 'int' // class D : System.Int32 { } Diagnostic(ErrorCode.ERR_CantDeriveFromSealedType, "System.Int32").WithArguments("N2.D", "int").WithLocation(5, 15)); } [Fact] public void CS0513ERR_AbstractInConcreteClass01() { var source = @"namespace NS { public class clx { abstract public void M1(); internal abstract object M2(); protected abstract internal void M3(sbyte p); public abstract object P { get; set; } } } "; CreateCompilation(source).VerifyDiagnostics( // (8,36): error CS0513: 'clx.P.get' is abstract but it is contained in non-abstract type 'clx' // public abstract object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("NS.clx.P.get", "NS.clx").WithLocation(8, 36), // (8,41): error CS0513: 'clx.P.set' is abstract but it is contained in non-abstract type 'clx' // public abstract object P { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("NS.clx.P.set", "NS.clx").WithLocation(8, 41), // (6,34): error CS0513: 'clx.M2()' is abstract but it is contained in non-abstract type 'clx' // internal abstract object M2(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M2").WithArguments("NS.clx.M2()", "NS.clx").WithLocation(6, 34), // (7,42): error CS0513: 'clx.M3(sbyte)' is abstract but it is contained in non-abstract type 'clx' // protected abstract internal void M3(sbyte p); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M3").WithArguments("NS.clx.M3(sbyte)", "NS.clx").WithLocation(7, 42), // (5,30): error CS0513: 'clx.M1()' is abstract but it is contained in non-abstract type 'clx' // abstract public void M1(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M1").WithArguments("NS.clx.M1()", "NS.clx").WithLocation(5, 30)); } [Fact] public void CS0513ERR_AbstractInConcreteClass02() { var text = @" class C { public abstract event System.Action E; public abstract int this[int x] { get; set; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0513: 'C.E' is abstract but it is contained in non-abstract type 'C' // public abstract event System.Action E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("C.E", "C"), // (5,39): error CS0513: 'C.this[int].get' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.this[int].get", "C"), // (5,44): error CS0513: 'C.this[int].set' is abstract but it is contained in non-abstract type 'C' // public abstract int this[int x] { get; set; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.this[int].set", "C")); } [Fact] public void CS0515ERR_StaticConstructorWithAccessModifiers01() { var text = @"namespace NS { static public class clx { private static clx() { } class C<T, V> { internal static C() { } } } public class clz { public static clz() { } struct S { internal static S() { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 5, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 9, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 15, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticConstructorWithAccessModifiers, Line = 19, Column = 29 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Some - /nostdlib - no mscorlib /// </summary> [Fact] public void CS0518ERR_PredefinedTypeNotFound01() { var text = @"namespace NS { class Test { static int Main() { return 1; } } } "; CreateEmptyCompilation(text).VerifyDiagnostics( // (3,11): error CS0518: Predefined type 'System.Object' is not defined or imported // class Test Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "Test").WithArguments("System.Object"), // (5,16): error CS0518: Predefined type 'System.Int32' is not defined or imported // static int Main() Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32"), // (7,20): error CS0518: Predefined type 'System.Int32' is not defined or imported // return 1; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "1").WithArguments("System.Int32"), // (3,11): error CS1729: 'object' does not contain a constructor that takes 0 arguments // class Test Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Test").WithArguments("object", "0")); } //[Fact(Skip = "Bad test case")] //public void CS0520ERR_PredefinedTypeBadType() //{ // var text = @""; // var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // new ErrorDescription { Code = (int)ErrorCode.ERR_PredefinedTypeBadType, Line = 5, Column = 26 } // ); //} [Fact] public void CS0523ERR_StructLayoutCycle01() { var text = @"struct A { A F; // CS0523 } struct B { C F; // CS0523 C G; // no additional error } struct C { B G; // CS0523 } struct D<T> { D<D<object>> F; // CS0523 } struct E { F<E> F; // no error } class F<T> { E G; // no error } struct G { H<G> F; // CS0523 } struct H<T> { G G; // CS0523 } struct J { static J F; // no error } struct K { static L F; // no error } struct L { static K G; // no error } "; CreateCompilation(text).VerifyDiagnostics( // (7,7): error CS0523: Struct member 'B.F' of type 'C' causes a cycle in the struct layout // C F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("B.F", "C").WithLocation(7, 7), // (12,7): error CS0523: Struct member 'C.G' of type 'B' causes a cycle in the struct layout // B G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("C.G", "B").WithLocation(12, 7), // (16,18): error CS0523: Struct member 'D<T>.F' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("D<T>.F", "D<D<object>>").WithLocation(16, 18), // (32,7): error CS0523: Struct member 'H<T>.G' of type 'G' causes a cycle in the struct layout // G G; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "G").WithArguments("H<T>.G", "G").WithLocation(32, 7), // (28,10): error CS0523: Struct member 'G.F' of type 'H<G>' causes a cycle in the struct layout // H<G> F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("G.F", "H<G>").WithLocation(28, 10), // (3,7): error CS0523: Struct member 'A.F' of type 'A' causes a cycle in the struct layout // A F; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("A.F", "A").WithLocation(3, 7), // (16,18): warning CS0169: The field 'D<T>.F' is never used // D<D<object>> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("D<T>.F").WithLocation(16, 18), // (32,7): warning CS0169: The field 'H<T>.G' is never used // G G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("H<T>.G").WithLocation(32, 7), // (12,7): warning CS0169: The field 'C.G' is never used // B G; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("C.G").WithLocation(12, 7), // (40,14): warning CS0169: The field 'K.F' is never used // static L F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("K.F").WithLocation(40, 14), // (28,10): warning CS0169: The field 'G.F' is never used // H<G> F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("G.F").WithLocation(28, 10), // (8,7): warning CS0169: The field 'B.G' is never used // C G; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(8, 7), // (36,14): warning CS0169: The field 'J.F' is never used // static J F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("J.F").WithLocation(36, 14), // (3,7): warning CS0169: The field 'A.F' is never used // A F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (20,10): warning CS0169: The field 'E.F' is never used // F<E> F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("E.F").WithLocation(20, 10), // (44,14): warning CS0169: The field 'L.G' is never used // static K G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("L.G").WithLocation(44, 14), // (7,7): warning CS0169: The field 'B.F' is never used // C F; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F").WithLocation(7, 7), // (24,7): warning CS0169: The field 'F<T>.G' is never used // E G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("F<T>.G").WithLocation(24, 7) ); } [Fact] public void CS0523ERR_StructLayoutCycle02() { var text = @"struct A { A P { get; set; } // CS0523 A Q { get; set; } // no additional error } struct B { C P { get; set; } // CS0523 (no error in Dev10!) } struct C { B Q { get; set; } // CS0523 (no error in Dev10!) } struct D<T> { D<D<object>> P { get; set; } // CS0523 } struct E { F<E> P { get; set; } // no error } class F<T> { E Q { get; set; } // no error } struct G { H<G> P { get; set; } // CS0523 G Q; // no additional error } struct H<T> { G Q; // CS0523 } struct J { static J P { get; set; } // no error } struct K { static L P { get; set; } // no error } struct L { static K Q { get; set; } // no error } struct M { N P { get; set; } // no error } struct N { M Q // no error { get { return new M(); } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,7): error CS0523: Struct member 'A.P' of type 'A' causes a cycle in the struct layout // A P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("A.P", "A"), // (8,7): error CS0523: Struct member 'B.P' of type 'C' causes a cycle in the struct layout // C P { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("B.P", "C"), // (12,7): error CS0523: Struct member 'C.Q' of type 'B' causes a cycle in the struct layout // B Q { get; set; } // CS0523 (no error in Dev10!) Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("C.Q", "B"), // (16,18): error CS0523: Struct member 'D<T>.P' of type 'D<D<object>>' causes a cycle in the struct layout // D<D<object>> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("D<T>.P", "D<D<object>>"), // (28,10): error CS0523: Struct member 'G.P' of type 'H<G>' causes a cycle in the struct layout // H<G> P { get; set; } // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "P").WithArguments("G.P", "H<G>"), // (33,7): error CS0523: Struct member 'H<T>.Q' of type 'G' causes a cycle in the struct layout // G Q; // CS0523 Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Q").WithArguments("H<T>.Q", "G"), // (29,7): warning CS0169: The field 'G.Q' is never used // G Q; // no additional error Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("G.Q"), // (33,7): warning CS0169: The field 'H<T>.Q' is never used // G Q; // CS0523 Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("H<T>.Q") ); } [WorkItem(540215, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540215")] [Fact] public void CS0523ERR_StructLayoutCycle03() { // Static fields should not be considered when // determining struct cycles. (Note: Dev10 does // report these cases as errors though.) var text = @"struct A { B F; // no error } struct B { static A G; // no error } "; CreateCompilation(text).VerifyDiagnostics( // (3,7): warning CS0169: The field 'A.F' is never used // B F; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("A.F").WithLocation(3, 7), // (7,14): warning CS0169: The field 'B.G' is never used // static A G; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "G").WithArguments("B.G").WithLocation(7, 14) ); } [WorkItem(541629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541629")] [Fact] public void CS0523ERR_StructLayoutCycle04() { var text = @"struct E { } struct X<T> { public T t; } struct Y { public X<Z> xz; } struct Z { public X<E> xe; public X<Y> xy; } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): error CS0523: Struct member 'Y.xz' of type 'X<Z>' causes a cycle in the struct layout // public X<Z> xz; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xz").WithArguments("Y.xz", "X<Z>").WithLocation(9, 17), // (14,17): error CS0523: Struct member 'Z.xy' of type 'X<Y>' causes a cycle in the struct layout // public X<Y> xy; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "xy").WithArguments("Z.xy", "X<Y>").WithLocation(14, 17), // (9,17): warning CS0649: Field 'Y.xz' is never assigned to, and will always have its default value // public X<Z> xz; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xz").WithArguments("Y.xz", "").WithLocation(9, 17), // (14,17): warning CS0649: Field 'Z.xy' is never assigned to, and will always have its default value // public X<Y> xy; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xy").WithArguments("Z.xy", "").WithLocation(14, 17), // (5,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", "").WithLocation(5, 14), // (13,17): warning CS0649: Field 'Z.xe' is never assigned to, and will always have its default value // public X<E> xe; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "xe").WithArguments("Z.xe", "").WithLocation(13, 17) ); } [WorkItem(541629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541629")] [Fact] public void CS0523ERR_StructLayoutCycle05() { var text = @"struct X<T> { public T t; } struct W<T> { X<W<W<T>>> x; }"; CreateCompilation(text).VerifyDiagnostics( // (8,16): error CS0523: Struct member 'W<T>.x' of type 'X<W<W<T>>>' causes a cycle in the struct layout // X<W<W<T>>> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("W<T>.x", "X<W<W<T>>>"), // (3,14): warning CS0649: Field 'X<T>.t' is never assigned to, and will always have its default value // public T t; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "t").WithArguments("X<T>.t", ""), // (8,16): warning CS0169: The field 'W<T>.x' is never used // X<W<W<T>>> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("W<T>.x") ); } [Fact] public void CS0523ERR_StructLayoutCycle06() { var text = @"struct S1<T, U> { S1<object, object> F; } struct S2<T, U> { S2<U, T> F; } struct S3<T> { T F; } struct S4<T> { S3<S3<T>> F; }"; CreateCompilation(text).VerifyDiagnostics( // (3,24): error CS0523: Struct member 'S1<T, U>.F' of type 'S1<object, object>' causes a cycle in the struct layout // S1<object, object> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S1<T, U>.F", "S1<object, object>").WithLocation(3, 24), // (7,14): error CS0523: Struct member 'S2<T, U>.F' of type 'S2<U, T>' causes a cycle in the struct layout // S2<U, T> F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S2<T, U>.F", "S2<U, T>").WithLocation(7, 14), // (7,14): warning CS0169: The field 'S2<T, U>.F' is never used // S2<U, T> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S2<T, U>.F").WithLocation(7, 14), // (11,7): warning CS0169: The field 'S3<T>.F' is never used // T F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S3<T>.F").WithLocation(11, 7), // (15,15): warning CS0169: The field 'S4<T>.F' is never used // S3<S3<T>> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S4<T>.F").WithLocation(15, 15), // (3,24): warning CS0169: The field 'S1<T, U>.F' is never used // S1<object, object> F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("S1<T, U>.F").WithLocation(3, 24) ); } [WorkItem(872954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872954")] [Fact] public void CS0523ERR_StructLayoutCycle07() { var text = @"struct S0<T> { static S0<T> x; } struct S1<T> { class C { } static S1<C> x; } struct S2<T> { struct S { } static S2<S> x; } struct S3<T> { interface I { } static S3<I> x; } struct S4<T> { delegate void D(); static S4<D> x; } struct S5<T> { enum E { } static S5<E> x; } struct S6<T> { static S6<T[]> x; }"; CreateCompilation(text).VerifyDiagnostics( // (8,18): error CS0523: Struct member 'S1<T>.x' of type 'S1<S1<T>.C>' causes a cycle in the struct layout // static S1<C> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S1<T>.x", "S1<S1<T>.C>").WithLocation(8, 18), // (13,18): error CS0523: Struct member 'S2<T>.x' of type 'S2<S2<T>.S>' causes a cycle in the struct layout // static S2<S> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S2<T>.x", "S2<S2<T>.S>").WithLocation(13, 18), // (18,18): error CS0523: Struct member 'S3<T>.x' of type 'S3<S3<T>.I>' causes a cycle in the struct layout // static S3<I> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S3<T>.x", "S3<S3<T>.I>").WithLocation(18, 18), // (23,18): error CS0523: Struct member 'S4<T>.x' of type 'S4<S4<T>.D>' causes a cycle in the struct layout // static S4<D> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S4<T>.x", "S4<S4<T>.D>").WithLocation(23, 18), // (28,18): error CS0523: Struct member 'S5<T>.x' of type 'S5<S5<T>.E>' causes a cycle in the struct layout // static S5<E> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S5<T>.x", "S5<S5<T>.E>").WithLocation(28, 18), // (32,20): error CS0523: Struct member 'S6<T>.x' of type 'S6<T[]>' causes a cycle in the struct layout // static S6<T[]> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("S6<T>.x", "S6<T[]>").WithLocation(32, 20), // (8,18): warning CS0169: The field 'S1<T>.x' is never used // static S1<C> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S1<T>.x").WithLocation(8, 18), // (23,18): warning CS0169: The field 'S4<T>.x' is never used // static S4<D> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S4<T>.x").WithLocation(23, 18), // (18,18): warning CS0169: The field 'S3<T>.x' is never used // static S3<I> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S3<T>.x").WithLocation(18, 18), // (3,18): warning CS0169: The field 'S0<T>.x' is never used // static S0<T> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S0<T>.x").WithLocation(3, 18), // (13,18): warning CS0169: The field 'S2<T>.x' is never used // static S2<S> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S2<T>.x").WithLocation(13, 18), // (28,18): warning CS0169: The field 'S5<T>.x' is never used // static S5<E> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S5<T>.x").WithLocation(28, 18), // (32,20): warning CS0169: The field 'S6<T>.x' is never used // static S6<T[]> x; Diagnostic(ErrorCode.WRN_UnreferencedField, "x").WithArguments("S6<T>.x").WithLocation(32, 20)); } [Fact] public void CS0524ERR_InterfacesCannotContainTypes01() { var text = @"namespace NS { public interface IGoo { interface IBar { } public class cly {} struct S { } private enum E { zero, one } // internal delegate void MyDel(object p); // delegates not in scope yet } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (5,19): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // interface IBar { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "IBar").WithArguments("default interface implementation", "8.0").WithLocation(5, 19), // (6,22): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // public class cly {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "cly").WithArguments("default interface implementation", "8.0").WithLocation(6, 22), // (7,16): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // struct S { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "S").WithArguments("default interface implementation", "8.0").WithLocation(7, 16), // (8,22): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // private enum E { zero, one } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "E").WithArguments("default interface implementation", "8.0").WithLocation(8, 22) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0525ERR_InterfacesCantContainFields01() { var text = @"namespace NS { public interface IGoo { string field1; const ulong field2 = 0; public IGoo field3; } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (5,16): error CS0525: Interfaces cannot contain instance fields // string field1; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "field1").WithLocation(5, 16), // (6,21): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // const ulong field2 = 0; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "field2").WithArguments("default interface implementation", "8.0").WithLocation(6, 21), // (7,21): error CS0525: Interfaces cannot contain instance fields // public IGoo field3; Diagnostic(ErrorCode.ERR_InterfacesCantContainFields, "field3").WithLocation(7, 21) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0526ERR_InterfacesCantContainConstructors01() { var text = @"namespace NS { public interface IGoo { public IGoo() {} internal IGoo(object p1, ref long p2) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 5, Column = 17 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfacesCantContainConstructors, Line = 6, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0527ERR_NonInterfaceInInterfaceList01() { var text = @"namespace NS { class C { } public struct S : object, C { interface IGoo : C { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 23 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 5, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NonInterfaceInInterfaceList, Line = 7, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0528ERR_DuplicateInterfaceInBaseList01() { var text = @"namespace NS { public interface IGoo {} public interface IBar { } public class C : IGoo, IGoo { } struct S : IBar, IGoo, IBar { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 5, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateInterfaceInBaseList, Line = 8, Column = 28 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } /// <summary> /// Extra errors - expected /// </summary> [Fact] public void CS0529ERR_CycleInInterfaceInheritance01() { var text = @"namespace NS { class AA : BB { } class BB : CC { } class CC : I3 { } interface I1 : I2 { } interface I2 : I3 { } interface I3 : I1 { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 7, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 8, Column = 15 }, // Extra new ErrorDescription { Code = (int)ErrorCode.ERR_CycleInInterfaceInheritance, Line = 9, Column = 15 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0531ERR_InterfaceMemberHasBody01() { var text = @"namespace NS { public interface IGoo { int M1() { return 0; } // CS0531 void M2<T>(T t) { } object P { get { return null; } } } interface IBar<T, V> { V M1(T t) { return default(V); } void M2(ref T t, out V v) { v = default(V); } T P { get { return default(T) } set { } } } } "; var comp = CreateCompilation(text, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (14,39): error CS1002: ; expected // T P { get { return default(T) } set { } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(14, 39) ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void AbstractConstructor() { var text = @"namespace NS { public class C { abstract C(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadMemberFlag, Line = 5, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void StaticFixed() { var text = @"unsafe struct S { public static fixed int x[10]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'static' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("static")); } [WorkItem(895401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895401")] [Fact] public void VolatileFixed() { var text = @"unsafe struct S { public volatile fixed int x[10]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,29): error CS0106: The modifier 'volatile' is not valid for this item // public static fixed int x[10]; Diagnostic(ErrorCode.ERR_BadMemberFlag, "x").WithArguments("volatile")); } [WorkItem(895401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/895401")] [Fact] public void ReadonlyConst() { var text = @" class C { private readonly int F1 = 123; private const int F2 = 123; private readonly const int F3 = 123; }"; CreateCompilation(text).VerifyDiagnostics( // (6,32): error CS0106: The modifier 'readonly' is not valid for this item // private readonly const int F3 = 123; Diagnostic(ErrorCode.ERR_BadMemberFlag, "F3").WithArguments("readonly"), // (4,26): warning CS0414: The field 'C.F1' is assigned but its value is never used // private readonly int F1 = 123; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F1").WithArguments("C.F1")); } [Fact] public void CS0533ERR_HidingAbstractMethod() { var text = @"namespace x { abstract public class a { abstract public void f(); abstract public void g(); } abstract public class b : a { new abstract public void f(); // CS0533 new abstract internal void g(); //fine since internal public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_HidingAbstractMethod, Line = 11, Column = 34 }); } [WorkItem(539629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539629")] [Fact] public void CS0533ERR_HidingAbstractMethod02() { var text = @" abstract public class B1 { public abstract float goo { set; } } abstract class A1 : B1 { new protected enum goo { } // CS0533 abstract public class B2 { protected abstract void goo(); } abstract class A2 : B2 { new public delegate object goo(); // CS0533 } } namespace NS { abstract public class B3 { public abstract void goo(); } abstract class A3 : B3 { new protected double[] goo; // CS0533 } } "; CreateCompilation(text).VerifyDiagnostics( // (31,32): error CS0533: 'A3.goo' hides inherited abstract member 'B3.goo()' // new protected double[] goo; // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("NS.A3.goo", "NS.B3.goo()").WithLocation(31, 32), // (9,24): error CS0533: 'A1.goo' hides inherited abstract member 'B1.goo' // new protected enum goo { } // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("A1.goo", "B1.goo").WithLocation(9, 24), // (18,36): error CS0533: 'A1.A2.goo' hides inherited abstract member 'A1.B2.goo()' // new public delegate object goo(); // CS0533 Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "goo").WithArguments("A1.A2.goo", "A1.B2.goo()").WithLocation(18, 36), // (31,32): warning CS0649: Field 'A3.goo' is never assigned to, and will always have its default value null // new protected double[] goo; // CS0533 Diagnostic(ErrorCode.WRN_UnassignedInternalField, "goo").WithArguments("NS.A3.goo", "null").WithLocation(31, 32)); } [WorkItem(540464, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540464")] [Fact] public void CS0533ERR_HidingAbstractMethod03() { var text = @" public abstract class A { public abstract void f(); public abstract void g(); public abstract void h(); } public abstract class B : A { public override void g() { } } public abstract class C : B { public void h(int a) { } } public abstract class D: C { public new int f; // expected CS0533: 'C.f' hides inherited abstract member 'A.f()' public new int g; // no error public new int h; // no CS0533 here in Dev10, but I'm not sure why not. (VB gives error for this case) } "; CreateCompilation(text).VerifyDiagnostics( // (18,16): error CS0533: 'D.f' hides inherited abstract member 'A.f()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "f").WithArguments("D.f", "A.f()")); } [WorkItem(539629, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539629")] [Fact] public void CS0533ERR_HidingAbstractMethod_Combinations() { var text = @" abstract class Base { public abstract void M(); public abstract int P { get; set; } public abstract class C { } } abstract class Derived1 : Base { public new abstract void M(); public new abstract void P(); public new abstract void C(); } abstract class Derived2 : Base { public new abstract int M { get; set; } public new abstract int P { get; set; } public new abstract int C { get; set; } } abstract class Derived3 : Base { public new abstract class M { } public new abstract class P { } public new abstract class C { } } abstract class Derived4 : Base { public new void M() { } public new void P() { } public new void C() { } } abstract class Derived5 : Base { public new int M { get; set; } public new int P { get; set; } public new int C { get; set; } } abstract class Derived6 : Base { public new class M { } public new class P { } public new class C { } } abstract class Derived7 : Base { public new static void M() { } public new static int P { get; set; } public new static class C { } } abstract class Derived8 : Base { public new static int M = 1; public new static class P { }; public new const int C = 2; }"; // CONSIDER: dev10 reports each hidden accessor separately, but that seems silly CreateCompilation(text).VerifyDiagnostics( // (11,30): error CS0533: 'Derived1.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived1.M()", "Base.M()"), // (12,30): error CS0533: 'Derived1.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived1.P()", "Base.P"), // (18,29): error CS0533: 'Derived2.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived2.M", "Base.M()"), // (19,29): error CS0533: 'Derived2.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived2.P", "Base.P"), // (25,31): error CS0533: 'Derived3.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived3.M", "Base.M()"), // (26,31): error CS0533: 'Derived3.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived3.P", "Base.P"), // (32,21): error CS0533: 'Derived4.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived4.M()", "Base.M()"), // (33,21): error CS0533: 'Derived4.P()' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived4.P()", "Base.P"), // (39,20): error CS0533: 'Derived5.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived5.M", "Base.M()"), // (40,20): error CS0533: 'Derived5.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived5.P", "Base.P"), // (46,22): error CS0533: 'Derived6.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived6.M", "Base.M()"), // (47,22): error CS0533: 'Derived6.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived6.P", "Base.P"), // (53,28): error CS0533: 'Derived7.M()' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived7.M()", "Base.M()"), // (54,27): error CS0533: 'Derived7.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived7.P", "Base.P"), // (60,27): error CS0533: 'Derived8.M' hides inherited abstract member 'Base.M()' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "M").WithArguments("Derived8.M", "Base.M()"), // (61,20): error CS0533: 'Derived8.P' hides inherited abstract member 'Base.P' Diagnostic(ErrorCode.ERR_HidingAbstractMethod, "P").WithArguments("Derived8.P", "Base.P")); } [WorkItem(539585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539585")] [Fact] public void CS0534ERR_UnimplementedAbstractMethod() { var text = @" abstract class A<T> { public abstract void M(T t); } abstract class B<T> : A<T> { public abstract void M(string s); } class C : B<string> // CS0534 { public override void M(string s) { } static void Main() { } } public abstract class Base<T> { public abstract void M(T t); public abstract void M(int i); } public class Derived : Base<int> // CS0534 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 13, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 26, Column = 14 }); } [Fact] public void CS0535ERR_UnimplementedInterfaceMember() { var text = @"public interface A { void F(); } public class B : A { } // CS0535 A::F is not implemented "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 6, Column = 18 }); } [Fact] public void CS0537ERR_ObjectCantHaveBases() { var text = @"namespace System { public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateEmptyCompilation(text).VerifyDiagnostics( // (3,20): error CS0246: The type or namespace name 'ICloneable' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ICloneable").WithArguments("ICloneable"), // (3,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } //this should be the same as CS0537ERR_ObjectCantHaveBases, except without the second //error (about ICloneable not being defined) [Fact] public void CS0537ERR_ObjectCantHaveBases_OtherType() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; //compile without corlib, since otherwise this System.Object won't count as a special type CreateEmptyCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact] public void CS0537ERR_ObjectCantHaveBases_WithMsCorlib() { var text = @"namespace System { public interface ICloneable { } public class Object : ICloneable { } }"; // When System.Object is defined in both source and metadata, dev10 favors // the source version and reports ERR_ObjectCantHaveBases. CreateEmptyCompilation(text).VerifyDiagnostics( // (6,11): error CS0537: The class System.Object cannot have a base class or implement an interface Diagnostic(ErrorCode.ERR_ObjectCantHaveBases, "Object")); } [Fact] public void CS0538ERR_ExplicitInterfaceImplementationNotInterface() { var text = @"interface MyIFace { } public class MyClass { } class C : MyIFace { void MyClass.G() // CS0538, MyClass not an interface { } int MyClass.P { get { return 1; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 11, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitInterfaceImplementationNotInterface, Line = 14, Column = 9 }); } [Fact] public void CS0539ERR_InterfaceMemberNotFound() { var text = @"namespace x { interface I { void m(); } public class clx : I { void I.x() // CS0539 { } void I.m() { } public static int Main() { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceMemberNotFound, Line = 10, Column = 14 }); } [Fact] public void CS0540ERR_ClassDoesntImplementInterface() { var text = @"interface I { void m(); } public class Clx { void I.m() { } // CS0540 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ClassDoesntImplementInterface, Line = 8, Column = 10 }); } [Fact] public void CS0541ERR_ExplicitInterfaceImplementationInNonClassOrStruct() { var text = @"namespace x { interface IFace { void F(); int P { set; } } interface IFace2 : IFace { void IFace.F(); // CS0541 int IFace.P { set; } //CS0541 } } "; CreateCompilation(text, parseOptions: TestOptions.Regular7, targetFramework: TargetFramework.NetCoreApp).VerifyDiagnostics( // (11,20): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // void IFace.F(); // CS0541 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "F").WithArguments("default interface implementation", "8.0").WithLocation(11, 20), // (12,23): error CS8652: The feature 'default interface implementation' is not available in C# 7. Please use language version 8.0 or greater. // int IFace.P { set; } //CS0541 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "set").WithArguments("default interface implementation", "8.0").WithLocation(12, 23), // (12,23): error CS0501: 'IFace2.IFace.P.set' must declare a body because it is not marked abstract, extern, or partial // int IFace.P { set; } //CS0541 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "set").WithArguments("x.IFace2.x.IFace.P.set").WithLocation(12, 23), // (11,20): error CS0501: 'IFace2.IFace.F()' must declare a body because it is not marked abstract, extern, or partial // void IFace.F(); // CS0541 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "F").WithArguments("x.IFace2.x.IFace.F()").WithLocation(11, 20) ); } [Fact] public void CS0542ERR_MemberNameSameAsType01() { var comp = CreateCompilation( @"namespace NS { class NS { } // no error interface IM { void IM(); } // no error interface IP { object IP { get; } } // no error enum A { A } // no error class B { enum B { } } class C { static void C() { } } class D { object D { get; set; } } class E { int D, E, F; } class F { class F { } } class G { struct G { } } class H { delegate void H(); } class L { class L<T> { } } class K<T> { class K { } } class M<T> { interface M<U> { } } class N { struct N<T, U> { } } struct O { enum O { } } struct P { void P() { } } struct Q { static object Q { get; set; } } struct R { object Q, R; } struct S { class S { } } struct T { interface T { } } struct U { struct U { } } struct V { delegate void V(); } struct W { class W<T> { } } struct X<T> { class X { } } struct Y<T> { interface Y<U> { } } struct Z { struct Z<T, U> { } } } "); comp.VerifyDiagnostics( // (7,20): error CS0542: 'B': member names cannot be the same as their enclosing type // class B { enum B { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "B").WithArguments("B"), // (8,27): error CS0542: 'C': member names cannot be the same as their enclosing type // class C { static void C() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "C").WithArguments("C"), // (9,22): error CS0542: 'D': member names cannot be the same as their enclosing type // class D { object D { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "D").WithArguments("D"), // (10,22): error CS0542: 'E': member names cannot be the same as their enclosing type // class E { int D, E, F; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("E"), // (11,21): error CS0542: 'F': member names cannot be the same as their enclosing type // class F { class F { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "F").WithArguments("F"), // (12,22): error CS0542: 'G': member names cannot be the same as their enclosing type // class G { struct G { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "G").WithArguments("G"), // (13,29): error CS0542: 'H': member names cannot be the same as their enclosing type // class H { delegate void H(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "H").WithArguments("H"), // (14,21): error CS0542: 'L': member names cannot be the same as their enclosing type // class L { class L<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "L").WithArguments("L"), // (15,24): error CS0542: 'K': member names cannot be the same as their enclosing type // class K<T> { class K { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "K").WithArguments("K"), // (16,28): error CS0542: 'M': member names cannot be the same as their enclosing type // class M<T> { interface M<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "M").WithArguments("M"), // (17,22): error CS0542: 'N': member names cannot be the same as their enclosing type // class N { struct N<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "N").WithArguments("N"), // (18,21): error CS0542: 'O': member names cannot be the same as their enclosing type // struct O { enum O { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "O").WithArguments("O"), // (19,21): error CS0542: 'P': member names cannot be the same as their enclosing type // struct P { void P() { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "P").WithArguments("P"), // (20,30): error CS0542: 'Q': member names cannot be the same as their enclosing type // struct Q { static object Q { get; set; } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Q").WithArguments("Q"), // (21,26): error CS0542: 'R': member names cannot be the same as their enclosing type // struct R { object Q, R; } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "R").WithArguments("R"), // (22,22): error CS0542: 'S': member names cannot be the same as their enclosing type // struct S { class S { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "S").WithArguments("S"), // (23,26): error CS0542: 'T': member names cannot be the same as their enclosing type // struct T { interface T { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "T").WithArguments("T"), // (24,23): error CS0542: 'U': member names cannot be the same as their enclosing type // struct U { struct U { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "U").WithArguments("U"), // (25,30): error CS0542: 'V': member names cannot be the same as their enclosing type // struct V { delegate void V(); } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "V").WithArguments("V"), // (26,22): error CS0542: 'W': member names cannot be the same as their enclosing type // struct W { class W<T> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "W").WithArguments("W"), // (27,25): error CS0542: 'X': member names cannot be the same as their enclosing type // struct X<T> { class X { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "X").WithArguments("X"), // (28,29): error CS0542: 'Y': member names cannot be the same as their enclosing type // struct Y<T> { interface Y<U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Y").WithArguments("Y"), // (29,23): error CS0542: 'Z': member names cannot be the same as their enclosing type // struct Z { struct Z<T, U> { } } Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Z").WithArguments("Z"), // (10,19): warning CS0169: The field 'NS.E.D' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "D").WithArguments("NS.E.D"), // (10,22): warning CS0169: The field 'NS.E.E' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "E").WithArguments("NS.E.E"), // (10,25): warning CS0169: The field 'NS.E.F' is never used // class E { int D, E, F; } Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("NS.E.F"), // (21,23): warning CS0169: The field 'NS.R.Q' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "Q").WithArguments("NS.R.Q"), // (21,26): warning CS0169: The field 'NS.R.R' is never used // struct R { object Q, R; } Diagnostic(ErrorCode.WRN_UnreferencedField, "R").WithArguments("NS.R.R")); } [Fact] public void CS0542ERR_MemberNameSameAsType02() { // No errors for names from explicit implementations. var source = @"interface IM { void C(); } interface IP { object C { get; } } class C : IM, IP { void IM.C() { } object IP.C { get { return null; } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact(), WorkItem(529156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529156")] public void CS0542ERR_MemberNameSameAsType03() { CreateCompilation( @"class Item { public int this[int i] // CS0542 { get { return 0; } } } ").VerifyDiagnostics(); } [WorkItem(538633, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538633")] [Fact] public void CS0542ERR_MemberNameSameAsType04() { var source = @"class get_P { object P { get; set; } // CS0542 } class set_P { object P { set { } } // CS0542 } interface get_Q { object Q { get; } } class C : get_Q { public object Q { get; set; } } interface IR { object R { get; set; } } class get_R : IR { public object R { get; set; } // CS0542 } class set_R : IR { object IR.R { get; set; } }"; CreateCompilation(source).VerifyDiagnostics( // (3,16): error CS0542: 'get_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_P").WithLocation(3, 16), // (7,16): error CS0542: 'set_P': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_P").WithLocation(7, 16), // (23,23): error CS0542: 'get_R': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_R").WithLocation(23, 23)); } [Fact] public void CS0542ERR_MemberNameSameAsType05() { var source = @"namespace N1 { class get_Item { object this[object o] { get { return null; } set { } } // CS0542 } class set_Item { object this[object o] { get { return null; } set { } } // CS0542 } } namespace N2 { interface I { object this[object o] { get; set; } } class get_Item : I { public object this[object o] { get { return null; } set { } } // CS0542 } class set_Item : I { object I.this[object o] { get { return null; } set { } } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,33): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(5, 33), // (9,54): error CS0542: 'set_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("set_Item").WithLocation(9, 54), // (20,40): error CS0542: 'get_Item': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("get_Item").WithLocation(20, 40)); } /// <summary> /// Derived class with same name as base class /// property accessor metadata name. /// </summary> [Fact] public void CS0542ERR_MemberNameSameAsType06() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object B1() { } .method public abstract virtual instance void B2(object v) { } .property instance object P() { .get instance object A::B1() .set instance void A::B2(object v) } }"; var reference1 = CompileIL(source1); var source2 = @"class B0 : A { public override object P { get { return null; } set { } } } class B1 : A { public override object P { get { return null; } set { } } } class B2 : A { public override object P { get { return null; } set { } } } class get_P : A { public override object P { get { return null; } set { } } } class set_P : A { public override object P { get { return null; } set { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (72): error CS0542: 'B1': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "get").WithArguments("B1").WithLocation(7, 32), // (11,53): error CS0542: 'B2': member names cannot be the same as their enclosing type Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "set").WithArguments("B2").WithLocation(11, 53)); } /// <summary> /// Derived class with same name as base class /// event accessor metadata name. /// </summary> [WorkItem(530385, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530385")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void CS0542ERR_MemberNameSameAsType07() { var source1 = @".class public abstract A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance void B1(class [mscorlib]System.Action v) { } .method public abstract virtual instance void B2(class [mscorlib]System.Action v) { } .event [mscorlib]System.Action E { .addon instance void A::B1(class [mscorlib]System.Action); .removeon instance void A::B2(class [mscorlib]System.Action); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class B0 : A { public override event Action E; } class B1 : A { public override event Action E; } class B2 : A { public override event Action E; } class add_E : A { public override event Action E; } class remove_E : A { public override event Action E; }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (8,34): error CS0542: 'B1': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B1").WithLocation(8, 34), // (12,34): error CS0542: 'B2': member names cannot be the same as their enclosing type // public override event Action E; Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "E").WithArguments("B2").WithLocation(12, 34), // (16,34): warning CS0067: The event 'add_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("add_E.E").WithLocation(16, 34), // (12,34): warning CS0067: The event 'B2.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B2.E").WithLocation(12, 34), // (8,34): warning CS0067: The event 'B1.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B1.E").WithLocation(8, 34), // (20,34): warning CS0067: The event 'remove_E.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("remove_E.E").WithLocation(20, 34), // (4,34): warning CS0067: The event 'B0.E' is never used // public override event Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("B0.E").WithLocation(4, 34)); } [Fact] public void CS0544ERR_CantOverrideNonProperty() { var text = @"public class a { public int i; } public class b : a { public override int i// CS0544 { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CantOverrideNonProperty, Line = 8, Column = 25 }); } [Fact] public void CS0545ERR_NoGetToOverride() { var text = @"public class a { public virtual int i { set { } } } public class b : a { public override int i { get { return 0; } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoGetToOverride, Line = 13, Column = 9 }); } [WorkItem(539321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539321")] [Fact] public void CS0545ERR_NoGetToOverride_Regress() { var text = @"public class A { public virtual int P1 { private get; set; } public virtual int P2 { private get; set; } } public class C : A { public override int P1 { set { } } //fine public sealed override int P2 { set { } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,32): error CS0545: 'C.P2': cannot override because 'A.P2' does not have an overridable get accessor Diagnostic(ErrorCode.ERR_NoGetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.SetMethod.IsVirtual); Assert.False(classAProp1.GetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0546ERR_NoSetToOverride() { var text = @"public class a { public virtual int i { get { return 0; } } } public class b : a { public override int i { set { } // CS0546 error no set } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoSetToOverride, Line = 15, Column = 9 }); } [WorkItem(539321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539321")] [Fact] public void CS0546ERR_NoSetToOverride_Regress() { var text = @"public class A { public virtual int P1 { get; private set; } public virtual int P2 { get; private set; } } public class C : A { public override int P1 { get { return 0; } } //fine public sealed override int P2 { get { return 0; } } //CS0546 since we can't see A.P2.set to override it as sealed } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (10,32): error CS0546: 'C.P2': cannot override because 'A.P2' does not have an overridable set accessor Diagnostic(ErrorCode.ERR_NoSetToOverride, "P2").WithArguments("C.P2", "A.P2")); var classA = comp.GlobalNamespace.GetMember<NamedTypeSymbol>("A"); var classAProp1 = classA.GetMember<PropertySymbol>("P1"); Assert.True(classAProp1.IsVirtual); Assert.True(classAProp1.GetMethod.IsVirtual); Assert.False(classAProp1.SetMethod.IsVirtual); //NB: non-virtual since private } [Fact] public void CS0547ERR_PropertyCantHaveVoidType() { var text = @"interface I { void P { get; set; } } class C { internal void P { set { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 3, Column = 10 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyCantHaveVoidType, Line = 7, Column = 19 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors() { var text = @"interface I { object P { } } abstract class A { public abstract object P { } } class B { internal object P { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0548ERR_PropertyWithNoAccessors_Indexer() { var text = @"interface I { object this[int x] { } } abstract class A { public abstract object this[int x] { } } class B { internal object this[int x] { } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 3, Column = 12 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 7, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_PropertyWithNoAccessors, Line = 11, Column = 21 }); } [Fact] public void CS0549ERR_NewVirtualInSealed01() { var text = @"namespace NS { public sealed class Goo { public virtual void M1() { } internal virtual void M2<X>(X x) { } internal virtual int P1 { get; set; } } sealed class Bar<T> { internal virtual T M1(T t) { return t; } public virtual object P1 { get { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 5, Column = 29 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 7, Column = 40 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 12, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NewVirtualInSealed, Line = 13, Column = 36 }); } [Fact] public void CS0549ERR_NewVirtualInSealed02() { var text = @" public sealed class C { public virtual event System.Action E; public virtual event System.Action F { add { } remove { } } public virtual int this[int x] { get { return 0; } set { } } } "; // CONSIDER: it seems a little strange to report it on property accessors but on // events themselves. On the other hand, property accessors can have modifiers, // whereas event accessors cannot. CreateCompilation(text).VerifyDiagnostics( // (4,40): error CS0549: 'C.E' is a new virtual member in sealed type 'C' // public virtual event System.Action E; Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "E").WithArguments("C.E", "C"), // (5,40): error CS0549: 'C.F' is a new virtual member in sealed type 'C' // public virtual event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "F").WithArguments("C.F", "C"), // (6,38): error CS0549: 'C.this[int].get' is a new virtual member in sealed type 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "get").WithArguments("C.this[int].get", "C"), // (6,56): error CS0549: 'C.this[int].set' is a new virtual member in sealed type 'C' // public virtual int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_NewVirtualInSealed, "set").WithArguments("C.this[int].set", "C"), // (4,40): warning CS0067: The event 'C.E' is never used // public virtual event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0550ERR_ExplicitPropertyAddingAccessor() { var text = @"namespace x { interface ii { int i { get; } } public class a : ii { int ii.i { get { return 0; } set { } // CS0550 no set in interface } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyAddingAccessor, Line = 19, Column = 13 }); } [Fact] public void CS0551ERR_ExplicitPropertyMissingAccessor() { var text = @"interface ii { int i { get; set; } } public class a : ii { int ii.i { set { } } // CS0551 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedInterfaceMember, Line = 10, Column = 18 }, //CONSIDER: dev10 suppresses this new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitPropertyMissingAccessor, Line = 12, Column = 12 }); } [Fact] public void CS0552ERR_ConversionWithInterface() { var text = @" public interface I { } public class C { public static implicit operator I(C c) // CS0552 { return null; } public static implicit operator C(I i) // CS0552 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (77): error CS0552: 'C.implicit operator I(C)': user-defined conversions to or from an interface are not allowed // public static implicit operator I(C c) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "I").WithArguments("C.implicit operator I(C)"), // (11,37): error CS0552: 'C.implicit operator C(I)': user-defined conversions to or from an interface are not allowed // public static implicit operator C(I i) // CS0552 Diagnostic(ErrorCode.ERR_ConversionWithInterface, "C").WithArguments("C.implicit operator C(I)")); } [Fact] public void CS0553ERR_ConversionWithBase() { var text = @" public class B { } public class D : B { public static implicit operator B(D d) // CS0553 { return null; } } public struct C { public static implicit operator C?(object c) // CS0553 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,37): error CS0553: 'D.implicit operator B(D)': user-defined conversions to or from a base type are not allowed // public static implicit operator B(D d) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "B").WithArguments("D.implicit operator B(D)"), // (12,37): error CS0553: 'C.implicit operator C?(object)': user-defined conversions to or from a base type are not allowed // public static implicit operator C?(object c) // CS0553 Diagnostic(ErrorCode.ERR_ConversionWithBase, "C?").WithArguments("C.implicit operator C?(object)")); } [Fact] public void CS0554ERR_ConversionWithDerived() { var text = @" public class B { public static implicit operator B(D d) // CS0554 { return null; } } public class D : B {} "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0554: 'B.implicit operator B(D)': user-defined conversions to or from a derived type are not allowed // public static implicit operator B(D d) // CS0554 Diagnostic(ErrorCode.ERR_ConversionWithDerived, "B").WithArguments("B.implicit operator B(D)") ); } [Fact] public void CS0555ERR_IdentityConversion() { var text = @" public class MyClass { public static implicit operator MyClass(MyClass aa) // CS0555 { return new MyClass(); } } public struct S { public static implicit operator S?(S s) { return s; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0555: User-defined operator cannot convert a type to itself // public static implicit operator MyClass(MyClass aa) // CS0555 Diagnostic(ErrorCode.ERR_IdentityConversion, "MyClass"), // (11,37): error CS0555: User-defined operator cannot convert a type to itself // public static implicit operator S?(S s) { return s; } Diagnostic(ErrorCode.ERR_IdentityConversion, "S?") ); } [Fact] public void CS0556ERR_ConversionNotInvolvingContainedType() { var text = @" public class C { public static implicit operator int(string aa) // CS0556 { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,37): error CS0556: User-defined conversion must convert to or from the enclosing type // public static implicit operator int(string aa) // CS0556 Diagnostic(ErrorCode.ERR_ConversionNotInvolvingContainedType, "int") ); } [Fact] public void CS0557ERR_DuplicateConversionInClass() { var text = @"namespace x { public class ii { public class iii { public static implicit operator int(iii aa) { return 0; } public static explicit operator int(iii aa) { return 0; } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,45): error CS0557: Duplicate user-defined conversion in type 'x.ii.iii' // public static explicit operator int(iii aa) Diagnostic(ErrorCode.ERR_DuplicateConversionInClass, "int").WithArguments("x.ii.iii") ); } [Fact] public void CS0558ERR_OperatorsMustBeStatic() { var text = @"namespace x { public class ii { public class iii { static implicit operator int(iii aa) // CS0558, add public { return 0; } } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (75): error CS0558: User-defined operator 'x.ii.iii.implicit operator int(x.ii.iii)' must be declared static and public // static implicit operator int(iii aa) // CS0558, add public Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "int").WithArguments("x.ii.iii.implicit operator int(x.ii.iii)") ); } [Fact] public void CS0559ERR_BadIncDecSignature() { var text = @"public class iii { public static iii operator ++(int aa) // CS0559 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0559: The parameter type for ++ or -- operator must be the containing type // public static iii operator ++(int aa) // CS0559 Diagnostic(ErrorCode.ERR_BadIncDecSignature, "++")); } [Fact] public void CS0562ERR_BadUnaryOperatorSignature() { var text = @"public class iii { public static iii operator +(int aa) // CS0562 { return null; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0562: The parameter of a unary operator must be the containing type // public static iii operator +(int aa) // CS0562 Diagnostic(ErrorCode.ERR_BadUnaryOperatorSignature, "+") ); } [Fact] public void CS0563ERR_BadBinaryOperatorSignature() { var text = @"public class iii { public static int operator +(int aa, int bb) // CS0563 { return 0; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,32): error CS0563: One of the parameters of a binary operator must be the containing type // public static int operator +(int aa, int bb) // CS0563 Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+") ); } [Fact] public void CS0564ERR_BadShiftOperatorSignature() { var text = @" class C { public static int operator <<(C c1, C c2) // CS0564 { return 0; } public static int operator >>(int c1, int c2) // CS0564 { return 0; } static void Main() { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator <<(C c1, C c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, "<<"), // (8,32): error CS0564: The first operand of an overloaded shift operator must have the same type as the containing type, and the type of the second operand must be int // public static int operator >>(int c1, int c2) // CS0564 Diagnostic(ErrorCode.ERR_BadShiftOperatorSignature, ">>") ); } [Fact] public void CS0567ERR_InterfacesCantContainOperators() { var text = @" interface IA { int operator +(int aa, int bb); // CS0567 } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (4,17): error CS0558: User-defined operator 'IA.operator +(int, int)' must be declared static and public // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_OperatorsMustBeStatic, "+").WithArguments("IA.operator +(int, int)").WithLocation(4, 17), // (4,17): error CS0501: 'IA.operator +(int, int)' must declare a body because it is not marked abstract, extern, or partial // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "+").WithArguments("IA.operator +(int, int)").WithLocation(4, 17), // (4,17): error CS0563: One of the parameters of a binary operator must be the containing type // int operator +(int aa, int bb); // CS0567 Diagnostic(ErrorCode.ERR_BadBinaryOperatorSignature, "+").WithLocation(4, 17) ); } [Fact] public void CS0569ERR_CantOverrideBogusMethod() { var source1 = @".class abstract public A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_sealed() { } .method public abstract virtual instance void set_sealed(object o) { } } .class abstract public B extends A { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .method public abstract virtual instance object get_abstract() { } .method public abstract virtual instance void set_abstract(object o) { } .method public virtual final instance void set_sealed(object o) { ret } .method public virtual final instance object get_sealed() { ldnull ret } // abstract get, sealed set .property instance object P() { .get instance object B::get_abstract() .set instance void B::set_sealed(object) } // sealed get, abstract set .property instance object Q() { .get instance object B::get_sealed() .set instance void B::set_abstract(object) } }"; var reference1 = CompileIL(source1); var source2 = @"class C : B { public override object P { get { return 0; } } public override object Q { set { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (3,28): error CS0569: 'C.P': cannot override 'B.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "P").WithArguments("C.P", "B.P").WithLocation(3, 28), // (4,28): error CS0569: 'C.Q': cannot override 'B.Q' because it is not supported by the language Diagnostic(ErrorCode.ERR_CantOverrideBogusMethod, "Q").WithArguments("C.Q", "B.Q").WithLocation(4, 28)); } [Fact] public void CS8036ERR_FieldInitializerInStruct() { var text = @"namespace x { public class clx { public static void Main() { } } public struct cly { clx a = new clx(); // CS8036 int i = 7; // CS8036 const int c = 1; // no error static int s = 2; // no error } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,13): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // clx a = new clx(); // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "a").WithArguments("struct field initializers", "10.0").WithLocation(12, 13), // (13,13): error CS8773: Feature 'struct field initializers' is not available in C# 9.0. Please use language version 10.0 or greater. // int i = 7; // CS8036 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "i").WithArguments("struct field initializers", "10.0").WithLocation(13, 13), // (13,13): warning CS0414: The field 'cly.i' is assigned but its value is never used // int i = 7; // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("x.cly.i").WithLocation(13, 13), // (15,20): warning CS0414: The field 'cly.s' is assigned but its value is never used // static int s = 2; // no error Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("x.cly.s").WithLocation(15, 20)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,13): warning CS0414: The field 'cly.i' is assigned but its value is never used // int i = 7; // CS8036 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "i").WithArguments("x.cly.i").WithLocation(13, 13), // (15,20): warning CS0414: The field 'cly.s' is assigned but its value is never used // static int s = 2; // no error Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "s").WithArguments("x.cly.s").WithLocation(15, 20)); } [Fact] public void CS0568ERR_StructsCantContainDefaultConstructor01() { var text = @"namespace x { public struct S1 { public S1() {} struct S2<T> { S2() { } } } } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp5)); comp.VerifyDiagnostics( // (5,16): error CS8026: Feature 'parameterless struct constructors' is not available in C# 5. Please use language version 10.0 or greater. // public S1() {} Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "S1").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 16), // (9,13): error CS8026: Feature 'parameterless struct constructors' is not available in C# 5. Please use language version 10.0 or greater. // S2() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion5, "S2").WithArguments("parameterless struct constructors", "10.0").WithLocation(9, 13), // (9,13): error CS8938: The parameterless struct constructor must be 'public'. // S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(9, 13)); comp = CreateCompilation(text); comp.VerifyDiagnostics( // (9,13): error CS8918: The parameterless struct constructor must be 'public'. // S2() { } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S2").WithLocation(9, 13)); } [Fact] public void CS0575ERR_OnlyClassesCanContainDestructors() { var text = @"namespace x { public struct iii { ~iii() // CS0575 { } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_OnlyClassesCanContainDestructors, Line = 5, Column = 10 }); } [Fact] public void CS0576ERR_ConflictAliasAndMember01() { var text = @"namespace NS { class B { } } namespace NS { using System; using B = NS.B; class A { public static void Main(String[] args) { B b = null; if (b == b) {} } } struct S { B field; public void M(ref B p) { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (22,27): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // public void M(ref B p) { } Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,9): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B field; Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (15,13): error CS0576: Namespace 'NS' contains a definition conflicting with alias 'B' // B b = null; if (b == b) {} Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "B").WithArguments("B", "NS"), // (21,11): warning CS0169: The field 'NS.S.field' is never used // B field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.S.field") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(545463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545463")] [Fact] public void CS0576ERR_ConflictAliasAndMember02() { var source = @" namespace Globals.Errors.ResolveInheritance { using ConflictingAlias = BadUsingNamespace; public class ConflictingAlias { public class Nested { } } namespace BadUsingNamespace { public class UsingNotANamespace { } } class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error class Cls2 : ConflictingAlias::UsingNotANamespace { } // OK class Cls3 : global::Globals.Errors.ResolveInheritance.ConflictingAlias.Nested { } // OK } "; CreateCompilation(source).VerifyDiagnostics( // (12,18): error CS0576: Namespace 'Globals.Errors.ResolveInheritance' contains a definition conflicting with alias 'ConflictingAlias' // class Cls1 : ConflictingAlias.UsingNotANamespace { } // Error Diagnostic(ErrorCode.ERR_ConflictAliasAndMember, "ConflictingAlias").WithArguments("ConflictingAlias", "Globals.Errors.ResolveInheritance")); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_01() { var sourceA = @"#pragma warning disable 436 using System.Diagnostics; class Program { [Conditional("""")] Program() { } }"; var sourceB = @"namespace System.Diagnostics { public class ConditionalAttribute : Attribute { public ConditionalAttribute(string s) { } } }"; var comp = CreateCompilation(new[] { sourceA, sourceB }); comp.VerifyDiagnostics( // (5,6): error CS0577: The Conditional attribute is not valid on 'Program.Program()' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [Conditional("")] Program() { } Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional("""")").WithArguments("Program.Program()").WithLocation(5, 6)); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_02() { var source = @"using System.Diagnostics; class Program { [Conditional("""")] ~Program() { } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,6): error CS0577: The Conditional attribute is not valid on 'Program.~Program()' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [Conditional("")] ~Program() { } Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional("""")").WithArguments("Program.~Program()").WithLocation(4, 6)); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_03() { var source = @"using System.Diagnostics; class C { [Conditional("""")] public static C operator !(C c) => c; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,6): error CS0577: The Conditional attribute is not valid on 'C.operator !(C)' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [Conditional("")] public static C operator !(C c) => c; Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional("""")").WithArguments("C.operator !(C)").WithLocation(4, 6)); } [Fact] public void CS0577ERR_ConditionalOnSpecialMethod_04() { var text = @"interface I { void m(); } public class MyClass : I { [System.Diagnostics.Conditional(""a"")] // CS0577 void I.m() { } } "; CreateCompilation(text).VerifyDiagnostics( // (8,6): error CS0577: The Conditional attribute is not valid on 'MyClass.I.m()' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation // [System.Diagnostics.Conditional("a")] // CS0577 Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"System.Diagnostics.Conditional(""a"")").WithArguments("MyClass.I.m()").WithLocation(8, 6)); } [Fact] public void CS0578ERR_ConditionalMustReturnVoid() { var text = @"public class MyClass { [System.Diagnostics.ConditionalAttribute(""a"")] // CS0578 public int TestMethod() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,5): error CS0578: The Conditional attribute is not valid on 'MyClass.TestMethod()' because its return type is not void // [System.Diagnostics.ConditionalAttribute("a")] // CS0578 Diagnostic(ErrorCode.ERR_ConditionalMustReturnVoid, @"System.Diagnostics.ConditionalAttribute(""a"")").WithArguments("MyClass.TestMethod()").WithLocation(3, 5)); } [Fact] public void CS0579ERR_DuplicateAttribute() { var text = @"class A : System.Attribute { } class B : System.Attribute { } [A, A] class C { } [B][A][B] class D { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 3, Column = 5 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateAttribute, Line = 4, Column = 8 }); } [Fact, WorkItem(528872, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528872")] public void CS0582ERR_ConditionalOnInterfaceMethod() { var text = @"using System.Diagnostics; interface MyIFace { [ConditionalAttribute(""DEBUG"")] // CS0582 void zz(); } "; CreateCompilation(text).VerifyDiagnostics( // (4,5): error CS0582: The Conditional attribute is not valid on interface members // [ConditionalAttribute("DEBUG")] // CS0582 Diagnostic(ErrorCode.ERR_ConditionalOnInterfaceMethod, @"ConditionalAttribute(""DEBUG"")").WithLocation(4, 5)); } [Fact] public void CS0590ERR_OperatorCantReturnVoid() { var text = @" public class C { public static void operator +(C c1, C c2) { } public static implicit operator void(C c1) { } public static void operator +(C c) { } public static void operator >>(C c, int x) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c1, C c2) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (5,33): error CS0590: User-defined operators cannot return void // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "void"), // (5,46): error CS1547: Keyword 'void' cannot be used in this context // public static implicit operator void(C c1) { } Diagnostic(ErrorCode.ERR_NoVoidHere, "void"), // (6,33): error CS0590: User-defined operators cannot return void // public static void operator +(C c) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, "+"), // (73): error CS0590: User-defined operators cannot return void // public static void operator >>(C c, int x) { } Diagnostic(ErrorCode.ERR_OperatorCantReturnVoid, ">>") ); } [Fact] public void CS0591ERR_InvalidAttributeArgument() { var text = @"using System; [AttributeUsage(0)] // CS0591 class A : Attribute { } [AttributeUsageAttribute(0)] // CS0591 class B : Attribute { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (2,17): error CS0591: Invalid value for argument to 'AttributeUsage' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsage").WithLocation(2, 17), // (4,26): error CS0591: Invalid value for argument to 'AttributeUsageAttribute' attribute Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "0").WithArguments("AttributeUsageAttribute").WithLocation(4, 26)); } [Fact] public void CS0592ERR_AttributeOnBadSymbolType() { var text = @"using System; [AttributeUsage(AttributeTargets.Interface)] public class MyAttribute : Attribute { } [MyAttribute] // Generates CS0592 because MyAttribute is not valid for a class. public class A { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AttributeOnBadSymbolType, Line = 8, Column = 2 }); } [Fact()] public void CS0596ERR_ComImportWithoutUuidAttribute() { var text = @"using System.Runtime.InteropServices; namespace x { [ComImport] // CS0596 public class a { } public class b { public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ComImportWithoutUuidAttribute, Line = 5, Column = 6 }); } // CS0599: not used [Fact] public void CS0601ERR_DllImportOnInvalidMethod() { var text = @" using System.Runtime.InteropServices; public class C { [DllImport(""KERNEL32.DLL"")] extern int Goo(); // CS0601 [DllImport(""KERNEL32.DLL"")] static void Bar() { } // CS0601 } "; CreateCompilation(text, options: TestOptions.ReleaseDll).VerifyDiagnostics( // (6,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), // (9,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport")); } /// <summary> /// Dev10 doesn't report this error, but emits invalid metadata. /// When the containing type is being loaded TypeLoadException is thrown by the CLR. /// </summary> [Fact] public void CS7042ERR_DllImportOnGenericMethod() { var text = @" using System.Runtime.InteropServices; public class C<T> { class X { [DllImport(""KERNEL32.DLL"")] static extern void Bar(); } } public class C { [DllImport(""KERNEL32.DLL"")] static extern void Bar<T>(); } "; CreateCompilation(text).VerifyDiagnostics( // (8,10): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport"), // (15,6): error CS7042: cannot be applied to a method that is generic or contained in a generic type. Diagnostic(ErrorCode.ERR_DllImportOnGenericMethod, "DllImport")); } // CS0609ERR_NameAttributeOnOverride -> BreakChange [Fact] public void CS0610ERR_FieldCantBeRefAny() { var text = @"public class MainClass { System.TypedReference i; // CS0610 public static void Main() { } System.TypedReference Prop { get; set; } }"; CreateCompilation(text).VerifyDiagnostics( // (8,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference Prop { get; set; } Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,5): error CS0610: Field or property cannot be of type 'System.TypedReference' // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.ERR_FieldCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference"), // (3,27): warning CS0169: The field 'MainClass.i' is never used // System.TypedReference i; // CS0610 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("MainClass.i") ); } [Fact] public void CS0616ERR_NotAnAttributeClass() { var text = @"[CMyClass] // CS0616 public class CMyClass {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0616ERR_NotAnAttributeClass2() { var text = @"[CMyClass] // CS0616 public class CMyClassAttribute {} "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NotAnAttributeClass, Line = 1, Column = 2 }); } [Fact] public void CS0617ERR_BadNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyClass : Attribute { public MyClass(int sName) { Bad = sName; Bad2 = -1; } public readonly int Bad; public int Bad2; } [MyClass(5, Bad = 0)] class Class1 { } // CS0617 [MyClass(5, Bad2 = 0)] class Class2 { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgument, Line = 16, Column = 13 }); } [Fact] public void CS0620ERR_IndexerCantHaveVoidType() { var text = @"class MyClass { public static void Main() { MyClass test = new MyClass(); } void this[int intI] // CS0620, return type cannot be void { get { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerCantHaveVoidType, Line = 8, Column = 10 }); } [Fact] public void CS0621ERR_VirtualPrivate01() { var text = @"namespace x { class Goo { private virtual void vf() { } } public class Bar<T> { private virtual void M1(T t) { } virtual V M2<V>(T t); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 9, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 19 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("x").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0621ERR_VirtualPrivate02() { var source = @"abstract class A { abstract object P { get; } } class B { private virtual object Q { get; set; } } "; CreateCompilation(source).VerifyDiagnostics( // (3,21): error CS0621: 'A.P': virtual or abstract members cannot be private // abstract object P { get; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "P").WithArguments("A.P").WithLocation(3, 21), // (7,28): error CS0621: 'B.Q': virtual or abstract members cannot be private // private virtual object Q { get; set; } Diagnostic(ErrorCode.ERR_VirtualPrivate, "Q").WithArguments("B.Q").WithLocation(7, 28)); } [Fact] public void CS0621ERR_VirtualPrivate03() { var text = @"namespace x { abstract class Goo { private virtual void M1<T>(T x) { } private abstract int P { get; set; } } class Bar { private override void M1<T>(T a) { } private override int P { set { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 5, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 6, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_VirtualPrivate, Line = 11, Column = 30 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 10, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_OverrideNotExpected, Line = 11, Column = 30 }); } [Fact] public void CS0621ERR_VirtualPrivate04() { var text = @" class C { virtual private event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (4,41): error CS0621: 'C.E': virtual or abstract members cannot be private // virtual private event System.Action E; Diagnostic(ErrorCode.ERR_VirtualPrivate, "E").WithArguments("C.E"), // (4,41): warning CS0067: The event 'C.E' is never used // virtual private event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } // CS0625: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0629ERR_InterfaceImplementedByConditional01() { var text = @"interface MyInterface { void MyMethod(); } public class MyClass : MyInterface { [System.Diagnostics.Conditional(""debug"")] public void MyMethod() // CS0629, remove the Conditional attribute { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InterfaceImplementedByConditional, Line = 9, Column = 17 }); } [Fact] public void CS0629ERR_InterfaceImplementedByConditional02() { var source = @" using System.Diagnostics; interface I<T> { void M(T x); } class Base { [Conditional(""debug"")] public void M(int x) {} } class Derived : Base, I<int> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,23): error CS0629: Conditional member 'Base.M(int)' cannot implement interface member 'I<int>.M(int)' in type 'Derived' // class Derived : Base, I<int> Diagnostic(ErrorCode.ERR_InterfaceImplementedByConditional, "I<int>").WithArguments("Base.M(int)", "I<int>.M(int)", "Derived").WithLocation(13, 23)); } [Fact] public void CS0633ERR_BadArgumentToAttribute() { var text = @"#define DEBUG using System.Diagnostics; public class Test { [Conditional(""DEB+UG"")] // CS0633 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'Conditional' attribute must be a valid identifier // [Conditional("DEB+UG")] // CS0633 Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""DEB+UG""").WithArguments("Conditional").WithLocation(5, 18)); } [Fact] public void CS0633ERR_BadArgumentToAttribute_IndexerNameAttribute() { var text = @" using System.Runtime.CompilerServices; class A { [IndexerName(null)] int this[int x] { get { return 0; } set { } } } class B { [IndexerName("""")] int this[int x] { get { return 0; } set { } } } class C { [IndexerName("" "")] int this[int x] { get { return 0; } set { } } } class D { [IndexerName(""1"")] int this[int x] { get { return 0; } set { } } } class E { [IndexerName(""!"")] int this[int x] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, "null").WithArguments("IndexerName"), // (10,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""""").WithArguments("IndexerName"), // (15,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @""" """).WithArguments("IndexerName"), // (20,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""1""").WithArguments("IndexerName"), // (25,18): error CS0633: The argument to the 'IndexerName' attribute must be a valid identifier Diagnostic(ErrorCode.ERR_BadArgumentToAttribute, @"""!""").WithArguments("IndexerName")); } // CS0636: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors // CS0637: See AttributeTests_StructLayout.ExplicitFieldLayout_Errors [Fact] public void CS0641ERR_AttributeUsageOnNonAttributeClass() { var text = @"using System; [AttributeUsage(AttributeTargets.Method)] class A { } [System.AttributeUsageAttribute(AttributeTargets.Class)] class B { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (2,2): error CS0641: Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "AttributeUsage").WithArguments("AttributeUsage").WithLocation(2, 2), // (4,2): error CS0641: Attribute 'System.AttributeUsageAttribute' is only valid on classes derived from System.Attribute Diagnostic(ErrorCode.ERR_AttributeUsageOnNonAttributeClass, "System.AttributeUsageAttribute").WithArguments("System.AttributeUsageAttribute").WithLocation(4, 2)); } [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument() { var text = @"using System; [AttributeUsage(AttributeTargets.Class)] public class MyAttribute : Attribute { public MyAttribute() { } public int x; } [MyAttribute(x = 5, x = 6)] // CS0643, error setting x twice class MyClass { } public class MainClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNamedAttributeArgument, Line = 13, Column = 21 }); } [WorkItem(540923, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540923")] [Fact] public void CS0643ERR_DuplicateNamedAttributeArgument02() { var text = @"using System; [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] class MyAtt : Attribute { } [MyAtt] public class Test { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (2,39): error CS0643: 'AllowMultiple' duplicate named attribute argument // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_DuplicateNamedAttributeArgument, "AllowMultiple = false").WithArguments("AllowMultiple").WithLocation(2, 39), // (2,2): error CS76: There is no argument given that corresponds to the required formal parameter 'validOn' of 'AttributeUsageAttribute.AttributeUsageAttribute(AttributeTargets)' // [AttributeUsage(AllowMultiple = true, AllowMultiple = false)] Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "AttributeUsage(AllowMultiple = true, AllowMultiple = false)").WithArguments("validOn", "System.AttributeUsageAttribute.AttributeUsageAttribute(System.AttributeTargets)").WithLocation(2, 2) ); } [Fact] public void CS0644ERR_DeriveFromEnumOrValueType() { var source = @"using System; namespace N { class C : Enum { } class D : ValueType { } class E : Delegate { } static class F : MulticastDelegate { } static class G : Array { } } "; CreateCompilation(source).VerifyDiagnostics( // (5,15): error CS0644: 'D' cannot derive from special class 'ValueType' // class D : ValueType { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "ValueType").WithArguments("N.D", "System.ValueType").WithLocation(5, 15), // (6,15): error CS0644: 'E' cannot derive from special class 'Delegate' // class E : Delegate { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Delegate").WithArguments("N.E", "System.Delegate").WithLocation(6, 15), // (4,15): error CS0644: 'C' cannot derive from special class 'Enum' // class C : Enum { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Enum").WithArguments("N.C", "System.Enum").WithLocation(4, 15), // (8,22): error CS0644: 'G' cannot derive from special class 'Array' // static class G : Array { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "Array").WithArguments("N.G", "System.Array").WithLocation(8, 22), // (7,22): error CS0644: 'F' cannot derive from special class 'MulticastDelegate' // static class F : MulticastDelegate { } Diagnostic(ErrorCode.ERR_DeriveFromEnumOrValueType, "MulticastDelegate").WithArguments("N.F", "System.MulticastDelegate").WithLocation(7, 22)); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType() { var text = @"[System.Reflection.DefaultMemberAttribute(""x"")] // CS0646 class MyClass { public int this[int index] // an indexer { get { return 0; } } public int x = 0; } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DefaultMemberOnIndexedType, Line = 1, Column = 2 }); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType02() { var text = @" using System.Reflection; interface I { int this[int x] { set; } } [DefaultMember(""X"")] class Program : I { int I.this[int x] { set { } } //doesn't count as an indexer for CS0646 }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0646ERR_DefaultMemberOnIndexedType03() { var text = @" using System.Reflection; [DefaultMember(""This is definitely not a valid member name *#&#*"")] class Program { }"; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0653ERR_AbstractAttributeClass() { var text = @"using System; public abstract class MyAttribute : Attribute { } [My] // CS0653 class MyClass { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AbstractAttributeClass, Line = 7, Column = 2 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType() { var text = @"using System; class MyAttribute : Attribute { public decimal d = 0; public int e = 0; } [My(d = 0)] // CS0655 class C { public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadNamedAttributeArgumentType, Line = 9, Column = 5 }); } [Fact] public void CS0655ERR_BadNamedAttributeArgumentType_Dynamic() { var text = @" using System; public class C<T> { public enum D { A } } [A1(P = null)] // Dev11 error public class A1 : Attribute { public A1() { } public dynamic P { get; set; } } [A2(P = null)] // Dev11 ok (bug) public class A2 : Attribute { public A2() { } public dynamic[] P { get; set; } } [A3(P = 0)] // Dev11 error (bug) public class A3 : Attribute { public A3() { } public C<dynamic>.D P { get; set; } } [A4(P = null)] // Dev11 ok public class A4 : Attribute { public A4() { } public C<dynamic>.D[] P { get; set; } } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (6,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A1(P = null)] // Dev11 error Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P"), // (13,5): error CS0655: 'P' is not a valid named attribute argument because it is not a valid attribute parameter type // [A2(P = null)] // Dev11 ok (bug) Diagnostic(ErrorCode.ERR_BadNamedAttributeArgumentType, "P").WithArguments("P")); } [Fact] public void CS0656ERR_MissingPredefinedMember() { var text = @"namespace System { public class Object { } public struct Byte { } public struct Int16 { } public struct Int32 { } public struct Int64 { } public struct Single { } public struct Double { } public struct SByte { } public struct UInt32 { } public struct UInt64 { } public struct Char { } public struct Boolean { } public struct UInt16 { } public struct UIntPtr { } public struct IntPtr { } public class Delegate { } public class String { public int Length { get { return 10; } } } public class MulticastDelegate { } public class Array { } public class Exception { } public class Type { } public class ValueType { } public class Enum { } public interface IEnumerable { } public interface IDisposable { } public class Attribute { } public class ParamArrayAttribute { } public struct Void { } public struct RuntimeFieldHandle { } public struct RuntimeTypeHandle { } namespace Collections { public interface IEnumerable { } public interface IEnumerator { } } namespace Runtime { namespace InteropServices { public class OutAttribute { } } namespace CompilerServices { public class RuntimeHelpers { } } } namespace Reflection { public class DefaultMemberAttribute { } } public class Test { public unsafe static int Main() { string str = ""This is my test string""; fixed (char* ptr = str) { if (*(ptr + str.Length) != '\0') return 1; } return 0; } } }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyEmitDiagnostics( // (70,32): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RuntimeHelpers.get_OffsetToStringData' // fixed (char* ptr = str) Diagnostic(ErrorCode.ERR_MissingPredefinedMember, "str").WithArguments("System.Runtime.CompilerServices.RuntimeHelpers", "get_OffsetToStringData")); } // CS0662: see AttributeTests.InOutAttributes_Errors [Fact] public void CS0663ERR_OverloadRefOut01() { var text = @"namespace NS { public interface IGoo<T> { void M(T t); void M(ref T t); void M(out T t); } internal class CGoo { private struct SGoo { void M<T>(T t) { } void M<T>(ref T t) { } void M<T>(out T t) { } } public int RetInt(byte b, out int i) { return i; } public int RetInt(byte b, ref int j) { return 3; } public int RetInt(byte b, int k) { return 4; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (7,14): error CS0663: 'IGoo<T>' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' // void M(out T t); Diagnostic(ErrorCode.ERR_OverloadRefKind, "M").WithArguments("NS.IGoo<T>", "method", "out", "ref").WithLocation(7, 14), // (24,20): error CS0663: 'CGoo' cannot define an overloaded method that differs only on parameter modifiers 'ref' and 'out' // public int RetInt(byte b, ref int j) Diagnostic(ErrorCode.ERR_OverloadRefKind, "RetInt").WithArguments("NS.CGoo", "method", "ref", "out").WithLocation(24, 20), // (16,18): error CS0663: 'CGoo.SGoo' cannot define an overloaded method that differs only on parameter modifiers 'out' and 'ref' // void M<T>(out T t) { } Diagnostic(ErrorCode.ERR_OverloadRefKind, "M").WithArguments("NS.CGoo.SGoo", "method", "out", "ref").WithLocation(16, 18), // (21,20): error CS0269: Use of unassigned out parameter 'i' // return i; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "i").WithArguments("i").WithLocation(21, 20), // (21,13): error CS0177: The out parameter 'i' must be assigned to before control leaves the current method // return i; Diagnostic(ErrorCode.ERR_ParamUnassigned, "return i;").WithArguments("i").WithLocation(21, 13), // (16,18): error CS0177: The out parameter 't' must be assigned to before control leaves the current method // void M<T>(out T t) { } Diagnostic(ErrorCode.ERR_ParamUnassigned, "M").WithArguments("t").WithLocation(16, 18) ); } [Fact] public void CS0666ERR_ProtectedInStruct01() { var text = @"namespace NS { internal struct S1<T, V> { protected T field; protected internal void M(T t, V v) { } protected object P { get { return null; } } // Dev10 no error protected event System.Action E; struct S2 { protected void M1<X>(X p) { } protected internal R M2<X, R>(ref X p, R r) { return r; } protected internal object Q { get; set; } // Dev10 no error protected event System.Action E; } } } "; CreateCompilation(text).VerifyDiagnostics( // (5,21): error CS0666: 'NS.S1<T, V>.field': new protected member declared in struct // protected T field; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "field").WithArguments("NS.S1<T, V>.field"), // (7,26): error CS0666: 'NS.S1<T, V>.P': new protected member declared in struct // protected object P { get { return null; } } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "P").WithArguments("NS.S1<T, V>.P"), // (8,39): error CS0666: 'NS.S1<T, V>.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.E"), // (6,33): error CS0666: 'NS.S1<T, V>.M(T, V)': new protected member declared in struct // protected internal void M(T t, V v) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M").WithArguments("NS.S1<T, V>.M(T, V)"), // (14,39): error CS0666: 'NS.S1<T, V>.S2.Q': new protected member declared in struct // protected internal object Q { get; set; } // Dev10 no error Diagnostic(ErrorCode.ERR_ProtectedInStruct, "Q").WithArguments("NS.S1<T, V>.S2.Q"), // (15,43): error CS0666: 'NS.S1<T, V>.S2.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("NS.S1<T, V>.S2.E"), // (12,28): error CS0666: 'NS.S1<T, V>.S2.M1<X>(X)': new protected member declared in struct // protected void M1<X>(X p) { } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M1").WithArguments("NS.S1<T, V>.S2.M1<X>(X)"), // (13,34): error CS0666: 'NS.S1<T, V>.S2.M2<X, R>(ref X, R)': new protected member declared in struct // protected internal R M2<X, R>(ref X p, R r) { return r; } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "M2").WithArguments("NS.S1<T, V>.S2.M2<X, R>(ref X, R)"), // (5,21): warning CS0649: Field 'NS.S1<T, V>.field' is never assigned to, and will always have its default value // protected T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.S1<T, V>.field", ""), // (8,39): warning CS0067: The event 'NS.S1<T, V>.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.E"), // (15,43): warning CS0067: The event 'NS.S1<T, V>.S2.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.S1<T, V>.S2.E") ); } [Fact] public void CS0666ERR_ProtectedInStruct02() { var text = @"struct S { protected object P { get { return null; } } public int Q { get; protected set; } } struct C<T> { protected internal T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 4, Column = 35 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStruct, Line = 8, Column = 45 }); } [Fact] public void CS0666ERR_ProtectedInStruct03() { var text = @" struct S { protected event System.Action E; protected event System.Action F { add { } remove { } } protected int this[int x] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (4,35): error CS0666: 'S.E': new protected member declared in struct // protected event System.Action E; Diagnostic(ErrorCode.ERR_ProtectedInStruct, "E").WithArguments("S.E"), // (5,35): error CS0666: 'S.F': new protected member declared in struct // protected event System.Action F { add { } remove { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "F").WithArguments("S.F"), // (6,19): error CS0666: 'S.this[int]': new protected member declared in struct // protected int this[int x] { get { return 0; } set { } } Diagnostic(ErrorCode.ERR_ProtectedInStruct, "this").WithArguments("S.this[int]"), // (4,35): warning CS0067: The event 'S.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("S.E")); } [Fact] public void CS0668ERR_InconsistentIndexerNames() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { [IndexerName(""IName1"")] public int this[int index] // indexer declaration { get { return index; } set { } } [IndexerName(""IName2"")] public int this[string s] // CS0668, change IName2 to IName1 { get { return int.Parse(s); } set { } } void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InconsistentIndexerNames, Line = 19, Column = 16 }); } [Fact] public void CS0668ERR_InconsistentIndexerNames02() { var text = @" using System.Runtime.CompilerServices; class IndexerClass { public int this[int[] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (12,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (15,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (18,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } /// <summary> /// Same as 02, but with an explicit interface implementation between each pair. /// </summary> [Fact] public void CS0668ERR_InconsistentIndexerNames03() { var text = @" using System.Runtime.CompilerServices; interface I { int this[int[] index] { get; set; } int this[int[,] index] { get; set; } int this[int[,,] index] { get; set; } int this[int[,,,] index] { get; set; } int this[int[,,,,] index] { get; set; } int this[int[,,,,,] index] { get; set; } } class IndexerClass : I { int I.this[int[] index] { get { return 0; } set { } } public int this[int[] index] { get { return 0; } set { } } int I.this[int[,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from no attribute to A public int this[int[,] index] { get { return 0; } set { } } int I.this[int[,,] index] { get { return 0; } set { } } // transition from A to no attribute public int this[int[,,] index] { get { return 0; } set { } } int I.this[int[,,,] index] { get { return 0; } set { } } [IndexerName(""B"")] // transition from no attribute to B public int this[int[,,,] index] { get { return 0; } set { } } int I.this[int[,,,,] index] { get { return 0; } set { } } [IndexerName(""A"")] // transition from B to A public int this[int[,,,,] index] { get { return 0; } set { } } int I.this[int[,,,,,] index] { get { return 0; } set { } } } "; CreateCompilation(text).VerifyDiagnostics( // (23,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (28,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (33,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this"), // (38,16): error CS0668: Two indexers have different names; the IndexerName attribute must be used with the same name on every indexer within a type Diagnostic(ErrorCode.ERR_InconsistentIndexerNames, "this")); } [Fact()] public void CS0669ERR_ComImportWithUserCtor() { var text = @"using System.Runtime.InteropServices; [ComImport, Guid(""00000000-0000-0000-0000-000000000001"")] class TestClass { TestClass() // CS0669, delete constructor to resolve { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,5): error CS0669: A class with the ComImport attribute cannot have a user-defined constructor // TestClass() // CS0669, delete constructor to resolve Diagnostic(ErrorCode.ERR_ComImportWithUserCtor, "TestClass").WithLocation(5, 5)); } [Fact] public void CS0670ERR_FieldCantHaveVoidType01() { var text = @"namespace NS { public class Goo { void Field2 = 0; public void Field1; public struct SGoo { void Field1; internal void Field2; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,9): error CS0670: Field cannot have void type // void Field2 = 0; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (6,16): error CS0670: Field cannot have void type // public void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (10,13): error CS0670: Field cannot have void type // void Field1; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (11,22): error CS0670: Field cannot have void type // internal void Field2; Diagnostic(ErrorCode.ERR_FieldCantHaveVoidType, "void"), // (5,23): error CS0029: Cannot implicitly convert type 'int' to 'void' // void Field2 = 0; Diagnostic(ErrorCode.ERR_NoImplicitConv, "0").WithArguments("int", "void"), // (10,18): warning CS0169: The field 'NS.Goo.SGoo.Field1' is never used // void Field1; Diagnostic(ErrorCode.WRN_UnreferencedField, "Field1").WithArguments("NS.Goo.SGoo.Field1"), // (11,27): warning CS0649: Field 'NS.Goo.SGoo.Field2' is never assigned to, and will always have its default value // internal void Field2; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Field2").WithArguments("NS.Goo.SGoo.Field2", "") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0673ERR_SystemVoid01() { var source = @"namespace NS { using System; interface IGoo<T> { Void M(T t); } class Goo { extern Void GetVoid(); struct SGoo : IGoo<Void> { } } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_SystemVoid, "Void"), Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IGoo<Void>").WithArguments("NS.Goo.SGoo", "NS.IGoo<System.Void>.M(System.Void)"), Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "GetVoid").WithArguments("NS.Goo.GetVoid()")); } [Fact] public void CS0674ERR_ExplicitParamArray() { var text = @"using System; public class MyClass { public static void UseParams([ParamArray] int[] list) // CS0674 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitParamArray, Line = 4, Column = 35 }); } [Fact] public void CS0677ERR_VolatileStruct() { var text = @"class TestClass { private volatile long i; // CS0677 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,27): error CS0677: 'TestClass.i': a volatile field cannot be of the type 'long' // private volatile long i; // CS0677 Diagnostic(ErrorCode.ERR_VolatileStruct, "i").WithArguments("TestClass.i", "long"), // (3,27): warning CS0169: The field 'TestClass.i' is never used // private volatile long i; // CS0677 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i") ); } [Fact] public void CS0677ERR_VolatileStruct_TypeParameter() { var text = @" class C1<T> { volatile T f; // CS0677 } class C2<T> where T : class { volatile T f; } class C3<T> where T : struct { volatile T f; // CS0677 } class C4<T> where T : C1<int> { volatile T f; } interface I { } class C5<T> where T : I { volatile T f; // CS0677 } "; CreateCompilation(text).VerifyDiagnostics( // (4,16): error CS0677: 'C1<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C1<T>.f", "T"), // (14,16): error CS0677: 'C3<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C3<T>.f", "T"), // (26,16): error CS0677: 'C5<T>.f': a volatile field cannot be of the type 'T' Diagnostic(ErrorCode.ERR_VolatileStruct, "f").WithArguments("C5<T>.f", "T"), // (4,16): warning CS0169: The field 'C1<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C1<T>.f"), // (9,16): warning CS0169: The field 'C2<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C2<T>.f"), // (14,16): warning CS0169: The field 'C3<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C3<T>.f"), // (19,16): warning CS0169: The field 'C4<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C4<T>.f"), // (26,16): warning CS0169: The field 'C5<T>.f' is never used Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C5<T>.f")); } [Fact] public void CS0678ERR_VolatileAndReadonly() { var text = @"class TestClass { private readonly volatile int i; // CS0678 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,35): error CS0678: 'TestClass.i': a field cannot be both volatile and readonly // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.ERR_VolatileAndReadonly, "i").WithArguments("TestClass.i"), // (3,35): warning CS0169: The field 'TestClass.i' is never used // private readonly volatile int i; // CS0678 Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("TestClass.i")); } [Fact] public void CS0681ERR_AbstractField01() { var text = @"namespace NS { class Goo<T> { public abstract T field; struct SGoo { abstract internal Goo<object> field; } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,27): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // public abstract T field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (10,43): error CS0681: The modifier 'abstract' is not valid on fields. Try using a property instead. // abstract internal Goo<object> field; Diagnostic(ErrorCode.ERR_AbstractField, "field"), // (6,27): warning CS0649: Field 'NS.Goo<T>.field' is never assigned to, and will always have its default value // public abstract T field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Goo<T>.field", ""), // (10,43): warning CS0649: Field 'NS.Goo<T>.SGoo.field' is never assigned to, and will always have its default value null // abstract internal Goo<object> field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("NS.Goo<T>.SGoo.field", "null") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [WorkItem(546447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546447")] [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS0682ERR_BogusExplicitImpl() { var source1 = @".class interface public abstract I { .method public abstract virtual instance object get_P() { } .method public abstract virtual instance void set_P(object& v) { } .property instance object P() { .get instance object I::get_P() .set instance void I::set_P(object& v) } .method public abstract virtual instance void add_E(class [mscorlib]System.Action v) { } .method public abstract virtual instance void remove_E(class [mscorlib]System.Action& v) { } .event [mscorlib]System.Action E { .addon instance void I::add_E(class [mscorlib]System.Action v); .removeon instance void I::remove_E(class [mscorlib]System.Action& v); } }"; var reference1 = CompileIL(source1); var source2 = @"using System; class C1 : I { object I.get_P() { return null; } void I.set_P(ref object v) { } void I.add_E(Action v) { } void I.remove_E(ref Action v) { } } class C2 : I { object I.P { get { return null; } set { } } event Action I.E { add { } remove { } } }"; var compilation2 = CreateCompilation(source2, new[] { reference1 }); compilation2.VerifyDiagnostics( // (11,14): error CS0682: 'C2.I.P' cannot implement 'I.P' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "P").WithArguments("C2.I.P", "I.P").WithLocation(11, 14), // (16,20): error CS0682: 'C2.I.E' cannot implement 'I.E' because it is not supported by the language Diagnostic(ErrorCode.ERR_BogusExplicitImpl, "E").WithArguments("C2.I.E", "I.E").WithLocation(16, 20)); } [Fact] public void CS0683ERR_ExplicitMethodImplAccessor() { var text = @"interface IExample { int Test { get; } } class CExample : IExample { int IExample.get_Test() { return 0; } // CS0683 int IExample.Test { get { return 0; } } // correct } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitMethodImplAccessor, Line = 8, Column = 18 }); } [Fact] public void CS0685ERR_ConditionalWithOutParam() { var text = @"namespace NS { using System.Diagnostics; class Test { [Conditional(""DEBUG"")] void Debug(out int i) // CS0685 { i = 1; } [Conditional(""TRACE"")] void Trace(ref string p1, out string p2) // CS0685 { p2 = p1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (7,10): error CS0685: Conditional member 'NS.Test.Debug(out int)' cannot have an out parameter // [Conditional("DEBUG")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""DEBUG"")").WithArguments("NS.Test.Debug(out int)").WithLocation(7, 10), // (13,10): error CS0685: Conditional member 'NS.Test.Trace(ref string, out string)' cannot have an out parameter // [Conditional("TRACE")] Diagnostic(ErrorCode.ERR_ConditionalWithOutParam, @"Conditional(""TRACE"")").WithArguments("NS.Test.Trace(ref string, out string)").WithLocation(13, 10)); } [Fact] public void CS0686ERR_AccessorImplementingMethod() { var text = @"interface I { int get_P(); } class C : I { public int P { get { return 1; } // CS0686 } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AccessorImplementingMethod, Line = 10, Column = 9 }); } [Fact] public void CS0689ERR_DerivingFromATyVar01() { var text = @"namespace NS { interface IGoo<T, V> : V { } internal class A<T> : T // CS0689 { protected struct S : T { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 7, Column = 27 }, new ErrorDescription { Code = (int)ErrorCode.ERR_DerivingFromATyVar, Line = 9, Column = 30 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0692ERR_DuplicateTypeParameter() { var source = @"class C<T, T> where T : class { void M<U, V, U>() where U : new() { } }"; CreateCompilation(source).VerifyDiagnostics( // (1,12): error CS0692: Duplicate type parameter 'T' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "T").WithArguments("T").WithLocation(1, 12), // (4,18): error CS0692: Duplicate type parameter 'U' Diagnostic(ErrorCode.ERR_DuplicateTypeParameter, "U").WithArguments("U").WithLocation(4, 18)); } [Fact] public void CS0693WRN_TypeParameterSameAsOuterTypeParameter01() { var text = @"namespace NS { interface IGoo<T, V> { void M<T>(); } public struct S<T> { public class Outer<T, V> { class Inner<T> // CS0693 { } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 5, Column = 16, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 10, Column = 28, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_TypeParameterSameAsOuterTypeParameter, Line = 12, Column = 25, IsWarning = true }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0694ERR_TypeVariableSameAsParent01() { var text = @"namespace NS { interface IGoo { void M<M>(M m); // OK (constraint applies to types but not methods) } class C<C> { public struct S<T, S> { } } } "; CreateCompilation(text).VerifyDiagnostics( // (8,13): error CS0694: Type parameter 'C' has the same name as the containing type, or method // class C<C> Diagnostic(ErrorCode.ERR_TypeVariableSameAsParent, "C").WithArguments("C").WithLocation(8, 13), // (10,28): error CS0694: Type parameter 'S' has the same name as the containing type, or method // public struct S<T, S> Diagnostic(ErrorCode.ERR_TypeVariableSameAsParent, "S").WithArguments("S").WithLocation(10, 28) ); } [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations() { // Note: more detailed unification tests are in TypeUnificationTests.cs var text = @"interface I<T> { } class G1<T1, T2> : I<T1>, I<T2> { } // CS0695 class G2<T1, T2> : I<int>, I<T2> { } // CS0695 class G3<T1, T2> : I<int>, I<short> { } // fine class G4<T1, T2> : I<I<T1>>, I<T1> { } // fine class G5<T1, T2> : I<I<T1>>, I<T2> { } // CS0695 interface I2<T> : I<T> { } class G6<T1, T2> : I<T1>, I2<T2> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 3, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 5, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 11, Column = 7 }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 15, Column = 7 }); } [WorkItem(539517, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539517")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations2() { var text = @" interface I<T, S> { } class A<T, S> : I<I<T, T>, T>, I<I<T, S>, S> { } // CS0695 "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 4, Column = 7 }); } [WorkItem(539518, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539518")] [Fact] public void CS0695ERR_UnifyingInterfaceInstantiations3() { var text = @" class A<T, S> { class B : A<B, B> { } interface IA { } interface IB : B.IA, B.B.IA { } // fine } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute01() { var text = @"class C<T> : System.Attribute { } "; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (1,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class C<T> : System.Attribute Diagnostic(ErrorCode.ERR_FeatureInPreview, "System.Attribute").WithArguments("generic attributes").WithLocation(1, 14)); } [Fact] public void CS0698ERR_GenericDerivingFromAttribute02() { var text = @"class A : System.Attribute { } class B<T> : A { } class C<T> { class B : A { } }"; CreateCompilation(text, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (2,14): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class B<T> : A { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "A").WithArguments("generic attributes").WithLocation(2, 14), // (5,15): error CS8652: The feature 'generic attributes' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class B : A { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "A").WithArguments("generic attributes").WithLocation(5, 15)); } [Fact] public void CS0699ERR_TyVarNotFoundInConstraint() { var source = @"struct S<T> where T : class where U : struct { void M<U, V>() where T : new() where W : class { } }"; CreateCompilation(source).VerifyDiagnostics( // (3,11): error CS0699: 'S<T>' does not define type parameter 'U' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "U").WithArguments("U", "S<T>").WithLocation(3, 11), // (6,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'T' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "T").WithArguments("T", "S<T>.M<U, V>()").WithLocation(6, 15), // (7,15): error CS0699: 'S<T>.M<U, V>()' does not define type parameter 'W' Diagnostic(ErrorCode.ERR_TyVarNotFoundInConstraint, "W").WithArguments("W", "S<T>.M<U, V>()").WithLocation(7, 15)); } [Fact] public void CS0701ERR_BadBoundType() { var source = @"delegate void D(); enum E { } struct S { } sealed class A<T> { } class C { void M1<T>() where T : string { } void M2<T>() where T : D { } void M3<T>() where T : E { } void M4<T>() where T : S { } void M5<T>() where T : A<T> { } }"; CreateCompilation(source).VerifyDiagnostics( // (7,28): error CS0701: 'string' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "string").WithArguments("string").WithLocation(7, 28), // (8,28): error CS0701: 'D' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "D").WithArguments("D").WithLocation(8, 28), // (9,28): error CS0701: 'E' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "E").WithArguments("E").WithLocation(9, 28), // (10,28): error CS0701: 'S' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "S").WithArguments("S").WithLocation(10, 28), // (11,28): error CS0701: 'A<T>' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. Diagnostic(ErrorCode.ERR_BadBoundType, "A<T>").WithArguments("A<T>").WithLocation(11, 28)); } [Fact] public void CS0702ERR_SpecialTypeAsBound() { var source = @"using System; interface IA<T> where T : object { } interface IB<T> where T : System.Object { } interface IC<T, U> where T : ValueType { } interface ID<T> where T : Array { }"; CreateCompilation(source).VerifyDiagnostics( // (2,27): error CS0702: Constraint cannot be special class 'object' // interface IA<T> where T : object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(2, 27), // (3,27): error CS0702: Constraint cannot be special class 'object' // interface IB<T> where T : System.Object { } Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object").WithArguments("object").WithLocation(3, 27), // (4,30): error CS0702: Constraint cannot be special class 'System.ValueType' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "ValueType").WithArguments("System.ValueType").WithLocation(4, 30), // (5,27): error CS0702: Constraint cannot be special class 'System.Array' Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "Array").WithArguments("System.Array").WithLocation(5, 27)); } [Fact] public void CS07ERR_BadVisBound01() { var source = @"public class C1 { protected interface I<T> { } internal class A<T> { } public delegate void D<T>() where T : A<T>, I<T>; } public class C2 : C1 { protected struct S<T, U, V> where T : I<A<T>> where U : I<I<U>> where V : A<A<V>> { } internal void M<T, U, V>() where T : A<I<T>> where U : I<I<U>> where V : A<A<V>> { } }"; CreateCompilation(source).VerifyDiagnostics( // (5,43): error CS07: Inconsistent accessibility: constraint type 'C1.A<T>' is less accessible than 'C1.D<T>' // public delegate void D<T>() where T : A<T>, I<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "A<T>").WithArguments("C1.D<T>", "C1.A<T>").WithLocation(5, 43), // (5,49): error CS07: Inconsistent accessibility: constraint type 'C1.I<T>' is less accessible than 'C1.D<T>' // public delegate void D<T>() where T : A<T>, I<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "I<T>").WithArguments("C1.D<T>", "C1.I<T>").WithLocation(5, 49), // (14,19): error CS07: Inconsistent accessibility: constraint type 'C1.A<C1.I<T>>' is less accessible than 'C2.M<T, U, V>()' // where T : A<I<T>> Diagnostic(ErrorCode.ERR_BadVisBound, "A<I<T>>").WithArguments("C2.M<T, U, V>()", "C1.A<C1.I<T>>").WithLocation(14, 19), // (15,19): error CS07: Inconsistent accessibility: constraint type 'C1.I<C1.I<U>>' is less accessible than 'C2.M<T, U, V>()' // where U : I<I<U>> Diagnostic(ErrorCode.ERR_BadVisBound, "I<I<U>>").WithArguments("C2.M<T, U, V>()", "C1.I<C1.I<U>>").WithLocation(15, 19), // (10,19): error CS07: Inconsistent accessibility: constraint type 'C1.I<C1.A<T>>' is less accessible than 'C2.S<T, U, V>' // where T : I<A<T>> Diagnostic(ErrorCode.ERR_BadVisBound, "I<A<T>>").WithArguments("C2.S<T, U, V>", "C1.I<C1.A<T>>").WithLocation(10, 19), // (12,19): error CS07: Inconsistent accessibility: constraint type 'C1.A<C1.A<V>>' is less accessible than 'C2.S<T, U, V>' // where V : A<A<V>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "A<A<V>>").WithArguments("C2.S<T, U, V>", "C1.A<C1.A<V>>").WithLocation(12, 19)); } [Fact] public void CS07ERR_BadVisBound02() { var source = @"internal interface IA<T> { } public interface IB<T, U> { } public class A { public partial class B<T, U> { } public partial class B<T, U> where U : IB<U, IA<T>> { } public partial class B<T, U> where U : IB<U, IA<T>> { } } public partial class C { public partial void M<T>() where T : IA<T>; public partial void M<T>() where T : IA<T> { } }"; CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (6,44): error CS07: Inconsistent accessibility: constraint type 'IB<U, IA<T>>' is less accessible than 'A.B<T, U>' // public partial class B<T, U> where U : IB<U, IA<T>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IB<U, IA<T>>").WithArguments("A.B<T, U>", "IB<U, IA<T>>").WithLocation(6, 44), // (7,44): error CS07: Inconsistent accessibility: constraint type 'IB<U, IA<T>>' is less accessible than 'A.B<T, U>' // public partial class B<T, U> where U : IB<U, IA<T>> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IB<U, IA<T>>").WithArguments("A.B<T, U>", "IB<U, IA<T>>").WithLocation(7, 44), // (11,42): error CS07: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' // public partial void M<T>() where T : IA<T>; Diagnostic(ErrorCode.ERR_BadVisBound, "IA<T>").WithArguments("C.M<T>()", "IA<T>").WithLocation(11, 42), // (12,42): error CS07: Inconsistent accessibility: constraint type 'IA<T>' is less accessible than 'C.M<T>()' // public partial void M<T>() where T : IA<T> { } Diagnostic(ErrorCode.ERR_BadVisBound, "IA<T>").WithArguments("C.M<T>()", "IA<T>").WithLocation(12, 42)); } [Fact] public void CS0708ERR_InstanceMemberInStaticClass01() { var text = @"namespace NS { public static class Goo { int i; void M() { } internal object P { get; set; } event System.Action E; } static class Bar<T> { T field; T M(T x) { return x; } int Q { get { return 0; } } event System.Action<T> E; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (5,13): error CS0708: 'NS.Goo.i': cannot declare instance members in a static class // int i; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "i").WithArguments("NS.Goo.i"), // (7,25): error CS0708: 'NS.Goo.P': cannot declare instance members in a static class // internal object P { get; set; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "P").WithArguments("NS.Goo.P"), // (8,29): error CS0708: 'E': cannot declare instance members in a static class // event System.Action E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (6,14): error CS0708: 'M': cannot declare instance members in a static class // void M() { } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (13,11): error CS0708: 'NS.Bar<T>.field': cannot declare instance members in a static class // T field; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "field").WithArguments("NS.Bar<T>.field"), // (15,13): error CS0708: 'NS.Bar<T>.Q': cannot declare instance members in a static class // int Q { get { return 0; } } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "Q").WithArguments("NS.Bar<T>.Q"), // (16,32): error CS0708: 'E': cannot declare instance members in a static class // event System.Action<T> E; Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "E").WithArguments("E"), // (16,32): warning CS0067: The event 'NS.Bar<T>.E' is never used // event System.Action<T> E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Bar<T>.E"), // (8,29): warning CS0067: The event 'NS.Goo.E' is never used // event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("NS.Goo.E"), // (14,11): error CS0708: 'M': cannot declare instance members in a static class // T M(T x) { return x; } Diagnostic(ErrorCode.ERR_InstanceMemberInStaticClass, "M").WithArguments("M"), // (5,13): warning CS0169: The field 'NS.Goo.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("NS.Goo.i"), // (13,11): warning CS0169: The field 'NS.Bar<T>.field' is never used // T field; Diagnostic(ErrorCode.WRN_UnreferencedField, "field").WithArguments("NS.Bar<T>.field")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0709ERR_StaticBaseClass01() { var text = @"namespace NS { public static class Base { } public class Derived : Base { } static class Base1<T, V> { } sealed class Seal<T> : Base1<T, short> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 7, Column = 18 }, new ErrorDescription { Code = (int)ErrorCode.ERR_StaticBaseClass, Line = 15, Column = 18 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0710ERR_ConstructorInStaticClass01() { var text = @"namespace NS { public static class C { public C() {} C(string s) { } static class D<T, V> { internal D() { } internal D(params sbyte[] ary) { } } static C() { } // no error } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 5, Column = 16 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 6, Column = 9 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 10, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ConstructorInStaticClass, Line = 11, Column = 22 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0711ERR_DestructorInStaticClass() { var text = @"public static class C { ~C() // CS0711 { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DestructorInStaticClass, Line = 3, Column = 6 }); } [Fact] public void CS0712ERR_InstantiatingStaticClass() { var text = @" static class C { static void Main() { C c = new C(); //CS0712 } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): error CS07: Cannot declare a variable of static type 'C' Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "C").WithArguments("C"), // (6,15): error CS0712: Cannot create an instance of the static class 'C' Diagnostic(ErrorCode.ERR_InstantiatingStaticClass, "new C()").WithArguments("C")); } [Fact] public void CS07ERR_StaticDerivedFromNonObject01() { var source = @"namespace NS { public class Base { } public static class Derived : Base { } class Base1<T, V> { } static class D<V> : Base1<string, V> { } } "; CreateCompilation(source).VerifyDiagnostics( // (75): error CS07: Static class 'Derived' cannot derive from type 'Base'. Static classes must derive from object. // public static class Derived : Base Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Base").WithArguments("NS.Derived", "NS.Base").WithLocation(7, 35), // (15,25): error CS07: Static class 'D<V>' cannot derive from type 'Base1<string, V>'. Static classes must derive from object. // static class D<V> : Base1<string, V> Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "Base1<string, V>").WithArguments("NS.D<V>", "NS.Base1<string, V>").WithLocation(15, 25)); } [Fact] public void CS07ERR_StaticDerivedFromNonObject02() { var source = @"delegate void A(); struct B { } static class C : A { } static class D : B { } "; CreateCompilation(source).VerifyDiagnostics( // (4,18): error CS07: Static class 'D' cannot derive from type 'B'. Static classes must derive from object. // static class D : B { } Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "B").WithArguments("D", "B").WithLocation(4, 18), // (3,18): error CS07: Static class 'C' cannot derive from type 'A'. Static classes must derive from object. // static class C : A { } Diagnostic(ErrorCode.ERR_StaticDerivedFromNonObject, "A").WithArguments("C", "A").WithLocation(3, 18)); } [Fact] public void CS0714ERR_StaticClassInterfaceImpl01() { var text = @"namespace NS { interface I { } public static class C : I { } interface IGoo<T, V> { } static class D<V> : IGoo<string, V> { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,29): error CS0714: 'NS.C': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "I").WithArguments("NS.C", "NS.I"), // (15,25): error CS0714: 'NS.D<V>': static classes cannot implement interfaces Diagnostic(ErrorCode.ERR_StaticClassInterfaceImpl, "IGoo<string, V>").WithArguments("NS.D<V>", "NS.IGoo<string, V>")); } [Fact] public void CS0715ERR_OperatorInStaticClass() { var text = @" public static class C { public static C operator +(C c) // CS0715 { return c; } } "; // Note that Roslyn produces these three errors. The native compiler // produces only the first. We might consider suppressing the additional // "cascading" errors in Roslyn. CreateCompilation(text).VerifyDiagnostics( // (4,30): error CS0715: 'C.operator +(C)': static classes cannot contain user-defined operators // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_OperatorInStaticClass, "+").WithArguments("C.operator +(C)"), // (4,30): error CS0721: 'C': static types cannot be used as parameters // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "+").WithArguments("C"), // (4,19): error CS0722: 'C': static types cannot be used as return types // public static C operator +(C c) // CS0715 Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "C").WithArguments("C") ); } [Fact] public void CS0716ERR_ConvertToStaticClass() { var text = @" static class C { static void M(object o) { M((C)o); M((C)new object()); M((C)null); M((C)1); M((C)""a""); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)o").WithArguments("C"), // (7,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)new object()").WithArguments("C"), // (8,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)null").WithArguments("C"), // (9,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)1").WithArguments("C"), // (10,11): error CS0716: Cannot convert to static type 'C' Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)\"a\"").WithArguments("C")); } [Fact] public void CS7023ERR_StaticInIsAsOrIs() { // The C# specification states that it is always illegal // to use a static type with "is" and "as". The native // compiler allows it in some cases; Roslyn gives a warning // at level '/warn:5' or higher. var text = @" static class C { static void M(object o) { M(o as C); // legal in native M(new object() as C); // legal in native M(null as C); // legal in native M(1 as C); M(""a"" as C); M(o is C); // legal in native, no warning M(new object() is C); // legal in native, no warning M(null is C); // legal in native, warns M(1 is C); // legal in native, warns M(""a"" is C); // legal in native, warns } } "; var strictDiagnostics = new[] { // (6,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(o as C); // legal in native Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "o as C").WithArguments("C").WithLocation(6, 11), // (7,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(new object() as C); // legal in native Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "new object() as C").WithArguments("C").WithLocation(7, 11), // (8,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(null as C); // legal in native Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "null as C").WithArguments("C").WithLocation(8, 11), // (9,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(1 as C); Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "1 as C").WithArguments("C").WithLocation(9, 11), // (9,11): error CS0039: Cannot convert type 'int' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M(1 as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, "1 as C").WithArguments("int", "C").WithLocation(9, 11), // (10,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M("a" as C); Diagnostic(ErrorCode.WRN_StaticInAsOrIs, @"""a"" as C").WithArguments("C").WithLocation(10, 11), // (10,11): error CS0039: Cannot convert type 'string' to 'C' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion // M("a" as C); Diagnostic(ErrorCode.ERR_NoExplicitBuiltinConv, @"""a"" as C").WithArguments("string", "C").WithLocation(10, 11), // (12,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(o is C); // legal in native, no warning Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "o is C").WithArguments("C").WithLocation(12, 11), // (13,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(new object() is C); // legal in native, no warning Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "new object() is C").WithArguments("C").WithLocation(13, 11), // (14,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(null is C); // legal in native, warns Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "null is C").WithArguments("C").WithLocation(14, 11), // (14,11): warning CS0184: The given expression is never of the provided ('C') type // M(null is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is C").WithArguments("C").WithLocation(14, 11), // (15,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M(1 is C); // legal in native, warns Diagnostic(ErrorCode.WRN_StaticInAsOrIs, "1 is C").WithArguments("C").WithLocation(15, 11), // (15,11): warning CS0184: The given expression is never of the provided ('C') type // M(1 is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "1 is C").WithArguments("C").WithLocation(15, 11), // (16,11): warning CS7023: The second operand of an 'is' or 'as' operator may not be static type 'C' // M("a" is C); // legal in native, warns Diagnostic(ErrorCode.WRN_StaticInAsOrIs, @"""a"" is C").WithArguments("C").WithLocation(16, 11), // (16,11): warning CS0184: The given expression is never of the provided ('C') type // M("a" is C); // legal in native, warns Diagnostic(ErrorCode.WRN_IsAlwaysFalse, @"""a"" is C").WithArguments("C").WithLocation(16, 11) }; // in /warn:5 we diagnose "is" and "as" operators with a static type. var strictComp = CreateCompilation(text); strictComp.VerifyDiagnostics(strictDiagnostics); // these rest of the diagnostics correspond to those produced by the native compiler. var regularDiagnostics = strictDiagnostics.Where(d => !d.Code.Equals((int)ErrorCode.WRN_StaticInAsOrIs)).ToArray(); var regularComp = CreateCompilation(text, options: TestOptions.ReleaseDll.WithWarningLevel(4)); regularComp.VerifyDiagnostics(regularDiagnostics); } [Fact] public void CS0717ERR_ConstraintIsStaticClass() { var source = @"static class A { } class B { internal static class C { } } delegate void D<T, U>() where T : A where U : B.C;"; CreateCompilation(source).VerifyDiagnostics( // (4,15): error CS0717: 'A': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "A").WithArguments("A").WithLocation(4, 15), // (5,15): error CS0717: 'B.C': static classes cannot be used as constraints Diagnostic(ErrorCode.ERR_ConstraintIsStaticClass, "B.C").WithArguments("B.C").WithLocation(5, 15)); } [Fact] public void CS0718ERR_GenericArgIsStaticClass01() { var text = @"interface I<T> { } class C<T> { internal static void M() { } } static class S { static void M<T>() { I<S> i = null; C<S> c = null; C<S>.M(); M<S>(); object o = typeof(I<S>); } }"; CreateCompilation(text).VerifyDiagnostics( // (10,11): error CS0718: 'S': static types cannot be used as type arguments // I<S> i = null; Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(10, 11), // (11,11): error CS0718: 'S': static types cannot be used as type arguments // C<S> c = null; Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(11, 11), // (12,11): error CS0718: 'S': static types cannot be used as type arguments // C<S>.M(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(12, 11), // (13,9): error CS0718: 'S': static types cannot be used as type arguments // M<S>(); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "M<S>").WithArguments("S").WithLocation(13, 9), // (14,29): error CS0718: 'S': static types cannot be used as type arguments // object o = typeof(I<S>); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "S").WithArguments("S").WithLocation(14, 29), // (10,14): warning CS0219: The variable 'i' is assigned but its value is never used // I<S> i = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "i").WithArguments("i").WithLocation(10, 14), // (11,14): warning CS0219: The variable 'c' is assigned but its value is never used // C<S> c = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "c").WithArguments("c").WithLocation(11, 14) ); } [Fact] public void CS0719ERR_ArrayOfStaticClass01() { var text = @"namespace NS { public static class C { } static class D<T> { } class Test { public static int Main() { var ca = new C[] { null }; var cd = new D<long>[9]; return 1; } } } "; // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a local because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 14, Column = 26 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ArrayOfStaticClass, Line = 15, Column = 26 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void ERR_VarDeclIsStaticClass02() { // The native compiler produces two errors for "C[] X;" -- that C cannot be used // as the element type of an array, and that C[] is not a legal type for // a field because it is static. This seems unnecessary, redundant and wrong. // I've eliminated the second error; the first is sufficient to diagnose the issue. var text = @"namespace NS { public static class C { } static class D<T> { } class Test { C[] X; C Y; D<int> Z; } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (12,9): error CS0719: 'NS.C': array elements cannot be of static type // C[] X; Diagnostic(ErrorCode.ERR_ArrayOfStaticClass, "C").WithArguments("NS.C"), // (13,11): error CS07: Cannot declare a variable of static type 'NS.C' // C Y; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Y").WithArguments("NS.C"), // (14,16): error CS07: Cannot declare a variable of static type 'NS.D<int>' // D<int> Z; Diagnostic(ErrorCode.ERR_VarDeclIsStaticClass, "Z").WithArguments("NS.D<int>"), // (12,13): warning CS0169: The field 'NS.Test.X' is never used // C[] X; Diagnostic(ErrorCode.WRN_UnreferencedField, "X").WithArguments("NS.Test.X"), // (13,11): warning CS0169: The field 'NS.Test.Y' is never used // C Y; Diagnostic(ErrorCode.WRN_UnreferencedField, "Y").WithArguments("NS.Test.Y"), // (14,16): warning CS0169: The field 'NS.Test.Z' is never used // D<int> Z; Diagnostic(ErrorCode.WRN_UnreferencedField, "Z").WithArguments("NS.Test.Z")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0720ERR_IndexerInStaticClass() { var text = @"public static class Test { public int this[int index] // CS0720 { get { return 1; } set {} } static void Main() {} } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_IndexerInStaticClass, Line = 3, Column = 16 }); } [Fact] public void CS0721ERR_ParameterIsStaticClass01() { var text = @"namespace NS { public static class C { } public static class D<T> { } interface IGoo<T> { void M(D<T> d); // Dev10 no error? } class Test { public void F(C p) // CS0721 { } struct S { object M<T>(D<T> p1) // CS0721 { return null; } } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ParameterIsStaticClass, Line = 12, Column = 14, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 16, Column = 21 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ParameterIsStaticClass, Line = 22, Column = 20 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CS0721ERR_ParameterIsStaticClass02() { var source = @"static class S { } class C { S P { set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(4, 11)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass01() { var source = @"namespace NS { public static class C { } public static class D<T> { } interface IGoo<T> { D<T> M(); // Dev10 no error? } class Test { extern public C F(); // CS0722 // { // return default(C); // } struct S { extern D<sbyte> M(); // CS0722 // { // return default(D<sbyte>); // } } } }"; CreateCompilation(source).VerifyDiagnostics( // (12,14): warning CS8898: 'NS.D<T>': static types cannot be used as return types Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "M").WithArguments("NS.D<T>").WithLocation(12, 14), // (16,25): error CS0722: 'NS.C': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("NS.C").WithLocation(16, 25), // (23,29): error CS0722: 'NS.D<sbyte>': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "M").WithArguments("NS.D<sbyte>").WithLocation(23, 29), // (16,25): warning CS0626: Method, operator, or accessor 'NS.Test.F()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "F").WithArguments("NS.Test.F()").WithLocation(16, 25), // (23,29): warning CS0626: Method, operator, or accessor 'NS.Test.S.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.S.M()").WithLocation(23, 29)); } [Fact] public void CS0722ERR_ReturnTypeIsStaticClass02() { var source = @"static class S { } class C { S P { get { return null; } } }"; CreateCompilation(source).VerifyDiagnostics( // (4,11): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(4, 11)); } [WorkItem(530434, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530434")] [Fact(Skip = "530434")] public void CS0722ERR_ReturnTypeIsStaticClass03() { var source = @"static class S { } class C { public abstract S F(); public abstract S P { get; } public abstract S Q { set; } }"; CreateCompilation(source).VerifyDiagnostics( // (4,23): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "F").WithArguments("S").WithLocation(4, 23), // (4,23): error CS0513: 'C.F()' is abstract but it is contained in non-abstract type 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "F").WithArguments("C.F()", "C").WithLocation(4, 23), // (5,27): error CS0513: 'C.P.get' is abstract but it is contained in non-abstract type 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("C.P.get", "C").WithLocation(5, 27), // (6,27): error CS0513: 'C.Q.set' is abstract but it is contained in non-abstract type 'C' Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "set").WithArguments("C.Q.set", "C").WithLocation(6, 27), // (5,27): error CS0722: 'S': static types cannot be used as return types Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "get").WithArguments("S").WithLocation(5, 27), // (6,27): error CS0721: 'S': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "set").WithArguments("S").WithLocation(6, 27)); } [WorkItem(546540, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546540")] [Fact] public void CS0722ERR_ReturnTypeIsStaticClass04() { var source = @"static class S1 { } static class S2 { } class C { public static S1 operator-(C c) { return null; } public static implicit operator S2(C c) { return null; } }"; CreateCompilation(source).VerifyDiagnostics( // (5,19): error CS0722: 'S1': static types cannot be used as return types // public static S1 operator-(C c) Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S1").WithArguments("S1"), // (9,37): error CS0722: 'S2': static types cannot be used as return types // public static implicit operator S2(C c) { return null; } Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S2").WithArguments("S2") ); } [Fact] public void CS0729ERR_ForwardedTypeInThisAssembly() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Test))] public class Test { } "; CreateCompilation(csharp).VerifyDiagnostics( // (4,12): error CS0729: Type 'Test' is defined in this assembly, but a type forwarder is specified for it // [assembly: TypeForwardedTo(typeof(Test))] Diagnostic(ErrorCode.ERR_ForwardedTypeInThisAssembly, "TypeForwardedTo(typeof(Test))").WithArguments("Test")); } [Fact, WorkItem(38256, "https://github.com/dotnet/roslyn/issues/38256")] public void ParameterAndReturnTypesAreStaticClassesWarning() { var source = @" static class C {} interface I { void M1(C c); // 1 C M2(); // 2 C Prop { get; set; } // 3, 4 C this[C c] { get; set; } // 5, 6, 7 } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,10): warning CS8897: 'C': static types cannot be used as parameters // void M1(C c); // 1 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "M1").WithArguments("C").WithLocation(5, 10), // (6,7): warning CS8898: 'C': static types cannot be used as return types // C M2(); // 2 Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "M2").WithArguments("C").WithLocation(6, 7), // (7,14): warning CS8898: 'C': static types cannot be used as return types // C Prop { get; set; } // 3, 4 Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "get").WithArguments("C").WithLocation(7, 14), // (7,19): warning CS8897: 'C': static types cannot be used as parameters // C Prop { get; set; } // 3, 4 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "set").WithArguments("C").WithLocation(7, 19), // (8,7): warning CS8897: 'C': static types cannot be used as parameters // C this[C c] { get; set; } // 5, 6, 7 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "this").WithArguments("C").WithLocation(8, 7), // (8,19): warning CS8898: 'C': static types cannot be used as return types // C this[C c] { get; set; } // 5, 6, 7 Diagnostic(ErrorCode.WRN_ReturnTypeIsStaticClass, "get").WithArguments("C").WithLocation(8, 19), // (8,24): warning CS8897: 'C': static types cannot be used as parameters // C this[C c] { get; set; } // 5, 6, 7 Diagnostic(ErrorCode.WRN_ParameterIsStaticClass, "set").WithArguments("C").WithLocation(8, 24) ); comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(4)); comp.VerifyDiagnostics(); } [Fact] public void CS0730ERR_ForwardedTypeIsNested() { var text1 = @"public class C { public class CC { } } "; var text2 = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(C.CC))]"; var comp1 = CreateCompilation(text1); var compRef1 = new CSharpCompilationReference(comp1); var comp2 = CreateCompilation(text2, new MetadataReference[] { compRef1 }); comp2.VerifyDiagnostics( // (4,12): error CS0730: Cannot forward type 'C.CC' because it is a nested type of 'C' // [assembly: TypeForwardedTo(typeof(C.CC))] Diagnostic(ErrorCode.ERR_ForwardedTypeIsNested, "TypeForwardedTo(typeof(C.CC))").WithArguments("C.CC", "C")); } // See TypeForwarders.Cycle1, etc. //[Fact] //public void CS0731ERR_CycleInTypeForwarder() [Fact] public void CS0735ERR_InvalidFwdType() { var csharp = @" using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(string[]))] [assembly: TypeForwardedTo(typeof(System.Int32*))] "; CreateCompilation(csharp).VerifyDiagnostics( // (4,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(string[]))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(string[]))"), // (5,12): error CS0735: Invalid type specified as an argument for TypeForwardedTo attribute // [assembly: TypeForwardedTo(typeof(System.Int32*))] Diagnostic(ErrorCode.ERR_InvalidFwdType, "TypeForwardedTo(typeof(System.Int32*))")); } [Fact] public void CS0736ERR_CloseUnimplementedInterfaceMemberStatic() { var text = @"namespace CS0736 { interface ITest { int testMethod(int x); } class Program : ITest // CS0736 { public static int testMethod(int x) { return 0; } public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberStatic, Line = 8, Column = 21 }); } [Fact] public void CS0737ERR_CloseUnimplementedInterfaceMemberNotPublic() { var text = @"interface ITest { int Return42(); } struct Struct1 : ITest // CS0737 { int Return42() { return (42); } } public class Test { public static void Main(string[] args) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberNotPublic, Line = 6, Column = 18 }); } [Fact] public void CS0738ERR_CloseUnimplementedInterfaceMemberWrongReturnType() { var text = @" interface ITest { int TestMethod(); } public class Test : ITest { public void TestMethod() { } // CS0738 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_CloseUnimplementedInterfaceMemberWrongReturnType, Line = 7, Column = 21 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_1() { var text = @"[assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] [assembly: System.Runtime.CompilerServices.TypeForwardedTo(typeof(int))] namespace cs0739 { class Program { static void Main(string[] args) { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateTypeForwarder, Line = 2, Column = 12 }); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_2() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(System.Int32))] [assembly: TypeForwardedTo(typeof(int))] [assembly: TypeForwardedTo(typeof(List<string>))] [assembly: TypeForwardedTo(typeof(List<System.String>))] "; CreateCompilation(csharp).VerifyDiagnostics( // (6,12): error CS0739: 'int' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(int))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(int))").WithArguments("int"), // (9,12): error CS0739: 'System.Collections.Generic.List<string>' duplicate TypeForwardedToAttribute // [assembly: TypeForwardedTo(typeof(List<System.String>))] Diagnostic(ErrorCode.ERR_DuplicateTypeForwarder, "TypeForwardedTo(typeof(List<System.String>))").WithArguments("System.Collections.Generic.List<string>")); } [Fact] public void CS0739ERR_DuplicateTypeForwarder_3() { var csharp = @" using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(List<int>))] [assembly: TypeForwardedTo(typeof(List<char>))] [assembly: TypeForwardedTo(typeof(List<>))] "; CreateCompilation(csharp).VerifyDiagnostics(); } [Fact] public void CS0750ERR_PartialMethodInvalidModifier() { var text = @" public class Base { protected virtual void PartG() { } protected void PartH() { } protected virtual void PartI() { } } public partial class C : Base { public partial void PartA(); private partial void PartB(); protected partial void PartC(); internal partial void PartD(); virtual partial void PartE(); abstract partial void PartF(); override partial void PartG(); new partial void PartH(); sealed override partial void PartI(); [System.Runtime.InteropServices.DllImport(""none"")] extern partial void PartJ(); public static int Main() { return 1; } } "; CreateCompilation(text, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (19,25): error CS8793: Partial method 'C.PartA()' must have an implementation part because it has accessibility modifiers. // public partial void PartA(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartA").WithArguments("C.PartA()").WithLocation(19, 25), // (20,26): error CS8793: Partial method 'C.PartB()' must have an implementation part because it has accessibility modifiers. // private partial void PartB(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartB").WithArguments("C.PartB()").WithLocation(20, 26), // (21,28): error CS8793: Partial method 'C.PartC()' must have an implementation part because it has accessibility modifiers. // protected partial void PartC(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartC").WithArguments("C.PartC()").WithLocation(21, 28), // (22,27): error CS8793: Partial method 'C.PartD()' must have an implementation part because it has accessibility modifiers. // internal partial void PartD(); Diagnostic(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, "PartD").WithArguments("C.PartD()").WithLocation(22, 27), // (29,25): error CS0759: No defining declaration found for implementing declaration of partial method 'C.PartJ()' // extern partial void PartJ(); Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "PartJ").WithArguments("C.PartJ()").WithLocation(29, 25), // (23,26): error CS8796: Partial method 'C.PartE()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // virtual partial void PartE(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartE").WithArguments("C.PartE()").WithLocation(23, 26), // (24,27): error CS0750: A partial method cannot have the 'abstract' modifier // abstract partial void PartF(); Diagnostic(ErrorCode.ERR_PartialMethodInvalidModifier, "PartF").WithLocation(24, 27), // (25,27): error CS8796: Partial method 'C.PartG()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // override partial void PartG(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartG").WithArguments("C.PartG()").WithLocation(25, 27), // (26,22): error CS8796: Partial method 'C.PartH()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // new partial void PartH(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartH").WithArguments("C.PartH()").WithLocation(26, 22), // (27,34): error CS8796: Partial method 'C.PartI()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // sealed override partial void PartI(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartI").WithArguments("C.PartI()").WithLocation(27, 34), // (29,25): error CS8796: Partial method 'C.PartJ()' must have accessibility modifiers because it has a 'virtual', 'override', 'sealed', 'new', or 'extern' modifier. // extern partial void PartJ(); Diagnostic(ErrorCode.ERR_PartialMethodWithExtendedModMustHaveAccessMods, "PartJ").WithArguments("C.PartJ()").WithLocation(29, 25), // (25,27): error CS0507: 'C.PartG()': cannot change access modifiers when overriding 'protected' inherited member 'Base.PartG()' // override partial void PartG(); Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "PartG").WithArguments("C.PartG()", "protected", "Base.PartG()").WithLocation(25, 27), // (27,34): error CS0507: 'C.PartI()': cannot change access modifiers when overriding 'protected' inherited member 'Base.PartI()' // sealed override partial void PartI(); Diagnostic(ErrorCode.ERR_CantChangeAccessOnOverride, "PartI").WithArguments("C.PartI()", "protected", "Base.PartI()").WithLocation(27, 34), // (28,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [System.Runtime.InteropServices.DllImport("none")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "System.Runtime.InteropServices.DllImport").WithLocation(28, 6)); } [Fact] public void CS0751ERR_PartialMethodOnlyInPartialClass() { var text = @" public class C { partial void Part(); // CS0751 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyInPartialClass, Line = 5, Column = 18 }); } [Fact] public void CS0752ERR_PartialMethodCannotHaveOutParameters() { var text = @" namespace NS { public partial class C { partial void F(out int x); } } "; CreateCompilation(text, parseOptions: TestOptions.RegularWithExtendedPartialMethods).VerifyDiagnostics( // (7,22): error CS8795: Partial method 'C.F(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void F(out int x); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "F").WithArguments("NS.C.F(out int)").WithLocation(7, 22)); } [Fact] public void CS067ERR_ERR_PartialMisplaced() { var text = @" partial class C { partial int f; partial object P { get { return null; } } partial int this[int index] { get { return index; } } partial void M(); } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial int f; Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(4, 5), // (5,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial object P { get { return null; } } Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(5, 5), // (6,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type. // partial int this[int index] Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(6, 5), // (4,17): warning CS0169: The field 'C.f' is never used // partial int f; Diagnostic(ErrorCode.WRN_UnreferencedField, "f").WithArguments("C.f").WithLocation(4, 17)); } [Fact] public void CS0754ERR_PartialMethodNotExplicit() { var text = @" public interface IF { void Part(); } public partial class C : IF { partial void IF.Part(); //CS0754 public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodNotExplicit, Line = 8, Column = 21 }); } [Fact] public void CS0755ERR_PartialMethodExtensionDifference() { var text = @"static partial class C { static partial void M1(this object o); static partial void M1(object o) { } static partial void M2(object o) { } static partial void M2(this object o); }"; CreateCompilation(text).VerifyDiagnostics( // (4,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M1").WithLocation(4, 25), // (5,25): error CS0755: Both partial method declarations must be extension methods or neither may be an extension method Diagnostic(ErrorCode.ERR_PartialMethodExtensionDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0756ERR_PartialMethodOnlyOneLatent() { var text = @" public partial class C { partial void Part(); partial void Part(); // CS0756 public static int Main() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,18): error CS0756: A partial method may not have multiple defining declarations // partial void Part(); // CS0756 Diagnostic(ErrorCode.ERR_PartialMethodOnlyOneLatent, "Part").WithLocation(5, 18), // (5,18): error CS0111: Type 'C' already defines a member called 'Part' with the same parameter types // partial void Part(); // CS0756 Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Part").WithArguments("Part", "C").WithLocation(5, 18)); } [Fact] public void CS0757ERR_PartialMethodOnlyOneActual() { var text = @" public partial class C { partial void Part(); partial void Part() { } partial void Part() // CS0757 { } public static int Main() { return 1; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_PartialMethodOnlyOneActual, Line = 8, Column = 18 }); } [Fact] public void CS0758ERR_PartialMethodParamsDifference() { var text = @"partial class C { partial void M1(params object[] args); partial void M1(object[] args) { } partial void M2(int n, params object[] args) { } partial void M2(int n, object[] args); }"; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M1").WithLocation(4, 18), // (5,18): error CS0758: Both partial method declarations must use a parameter array or neither may use a parameter array Diagnostic(ErrorCode.ERR_PartialMethodParamsDifference, "M2").WithLocation(5, 18)); } [Fact] public void CS0759ERR_PartialMethodMustHaveLatent() { var text = @"partial class C { partial void M1() { } partial void M2(); }"; CreateCompilation(text).VerifyDiagnostics( // (3,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M1()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M1").WithArguments("C.M1()").WithLocation(3, 18)); } [WorkItem(5427, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/5427")] [Fact] public void CS0759ERR_PartialMethodMustHaveLatent_02() { var text = @"using System; static partial class EExtensionMethod { static partial void M(this Array a); } static partial class EExtensionMethod { static partial void M() { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,25): error CS0759: No defining declaration found for implementing declaration of partial method'EExtensionMethod.M()' Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("EExtensionMethod.M()").WithLocation(9, 25)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints01() { var source = @"interface IA<T> { } interface IB { } partial class C<X> { // Different constraints: partial void A1<T>() where T : struct; partial void A2<T, U>() where T : struct where U : IA<T>; partial void A3<T>() where T : IA<T>; partial void A4<T, U>() where T : struct, IA<T>; // Additional constraints: partial void B1<T>(); partial void B2<T>() where T : X, new(); partial void B3<T, U>() where T : IA<T>; // Missing constraints. partial void C1<T>() where T : class; partial void C2<T>() where T : class, new(); partial void C3<T, U>() where U : IB, IA<T>; // Same constraints, different order. partial void D1<T>() where T : IA<T>, IB { } partial void D2<T, U, V>() where V : T, U, X { } // Different constraint clauses. partial void E1<T, U>() where U : T { } // Additional constraint clause. partial void F1<T, U>() where T : class { } // Missing constraint clause. partial void G1<T, U>() where T : class where U : T { } // Same constraint clauses, different order. partial void H1<T, U>() where T : class where U : T { } partial void H2<T, U>() where T : class where U : T { } partial void H3<T, U, V>() where V : class where U : IB where T : IA<V> { } // Different type parameter names. partial void K1<T, U>() where T : class where U : IA<T> { } partial void K2<T, U>() where T : class where U : T, IA<U> { } } partial class C<X> { // Different constraints: partial void A1<T>() where T : class { } partial void A2<T, U>() where T : struct where U : IB { } partial void A3<T>() where T : IA<IA<T>> { } partial void A4<T, U>() where T : struct, IA<U> { } // Additional constraints: partial void B1<T>() where T : new() { } partial void B2<T>() where T : class, X, new() { } partial void B3<T, U>() where T : IB, IA<T> { } // Missing constraints. partial void C1<T>() { } partial void C2<T>() where T : class { } partial void C3<T, U>() where U : IA<T> { } // Same constraints, different order. partial void D1<T>() where T : IB, IA<T>; partial void D2<T, U, V>() where V : U, X, T; // Different constraint clauses. partial void E1<T, U>() where T : class; // Additional constraint clause. partial void F1<T, U>() where T : class where U : T; // Missing constraint clause. partial void G1<T, U>() where T : class; // Same constraint clauses, different order. partial void H1<T, U>() where U : T where T : class; partial void H2<T, U>() where U : class where T : U; partial void H3<T, U, V>() where T : IA<V> where U : IB where V : class; // Different type parameter names. partial void K1<U, T>() where T : class where U : IA<T>; partial void K2<T1, T2>() where T1 : class where T2 : T1, IA<T2>; }"; // Note: Errors are reported on A1, A2, ... rather than A1<T>, A2<T, U>, ... See bug #9396. CreateCompilation(source).VerifyDiagnostics( // (39,18): error CS0761: Partial method declarations of 'C<X>.A2<T, U>()' have inconsistent constraints for type parameter 'U' // partial void A2<T, U>() where T : struct where U : IB { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A2").WithArguments("C<X>.A2<T, U>()", "U").WithLocation(39, 18), // (40,18): error CS0761: Partial method declarations of 'C<X>.A3<T>()' have inconsistent constraints for type parameter 'T' // partial void A3<T>() where T : IA<IA<T>> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A3").WithArguments("C<X>.A3<T>()", "T").WithLocation(40, 18), // (41,18): error CS0761: Partial method declarations of 'C<X>.A4<T, U>()' have inconsistent constraints for type parameter 'T' // partial void A4<T, U>() where T : struct, IA<U> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A4").WithArguments("C<X>.A4<T, U>()", "T").WithLocation(41, 18), // (43,18): error CS0761: Partial method declarations of 'C<X>.B1<T>()' have inconsistent constraints for type parameter 'T' // partial void B1<T>() where T : new() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B1").WithArguments("C<X>.B1<T>()", "T").WithLocation(43, 18), // (44,18): error CS0761: Partial method declarations of 'C<X>.B2<T>()' have inconsistent constraints for type parameter 'T' // partial void B2<T>() where T : class, X, new() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B2").WithArguments("C<X>.B2<T>()", "T").WithLocation(44, 18), // (45,18): error CS0761: Partial method declarations of 'C<X>.B3<T, U>()' have inconsistent constraints for type parameter 'T' // partial void B3<T, U>() where T : IB, IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "B3").WithArguments("C<X>.B3<T, U>()", "T").WithLocation(45, 18), // (47,18): error CS0761: Partial method declarations of 'C<X>.C1<T>()' have inconsistent constraints for type parameter 'T' // partial void C1<T>() { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C1").WithArguments("C<X>.C1<T>()", "T").WithLocation(47, 18), // (48,18): error CS0761: Partial method declarations of 'C<X>.C2<T>()' have inconsistent constraints for type parameter 'T' // partial void C2<T>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C2").WithArguments("C<X>.C2<T>()", "T").WithLocation(48, 18), // (49,18): error CS0761: Partial method declarations of 'C<X>.C3<T, U>()' have inconsistent constraints for type parameter 'U' // partial void C3<T, U>() where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "C3").WithArguments("C<X>.C3<T, U>()", "U").WithLocation(49, 18), // (22,18): error CS0761: Partial method declarations of 'C<X>.E1<T, U>()' have inconsistent constraints for type parameter 'T' // partial void E1<T, U>() where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "E1").WithArguments("C<X>.E1<T, U>()", "T").WithLocation(22, 18), // (22,18): error CS0761: Partial method declarations of 'C<X>.E1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void E1<T, U>() where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "E1").WithArguments("C<X>.E1<T, U>()", "U").WithLocation(22, 18), // (24,18): error CS0761: Partial method declarations of 'C<X>.F1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void F1<T, U>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "F1").WithArguments("C<X>.F1<T, U>()", "U").WithLocation(24, 18), // (26,18): error CS0761: Partial method declarations of 'C<X>.G1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void G1<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "G1").WithArguments("C<X>.G1<T, U>()", "U").WithLocation(26, 18), // (29,18): error CS0761: Partial method declarations of 'C<X>.H2<T, U>()' have inconsistent constraints for type parameter 'T' // partial void H2<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "H2").WithArguments("C<X>.H2<T, U>()", "T").WithLocation(29, 18), // (29,18): error CS0761: Partial method declarations of 'C<X>.H2<T, U>()' have inconsistent constraints for type parameter 'U' // partial void H2<T, U>() where T : class where U : T { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "H2").WithArguments("C<X>.H2<T, U>()", "U").WithLocation(29, 18), // (32,18): error CS0761: Partial method declarations of 'C<X>.K1<T, U>()' have inconsistent constraints for type parameter 'T' // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "K1").WithArguments("C<X>.K1<T, U>()", "T").WithLocation(32, 18), // (32,18): error CS0761: Partial method declarations of 'C<X>.K1<T, U>()' have inconsistent constraints for type parameter 'U' // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "K1").WithArguments("C<X>.K1<T, U>()", "U").WithLocation(32, 18), // (32,18): warning CS8826: Partial method declarations 'void C<X>.K1<U, T>()' and 'void C<X>.K1<T, U>()' have differences in parameter names, parameter types, or return types. // partial void K1<T, U>() where T : class where U : IA<T> { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "K1").WithArguments("void C<X>.K1<U, T>()", "void C<X>.K1<T, U>()").WithLocation(32, 18), // (33,18): warning CS8826: Partial method declarations 'void C<X>.K2<T1, T2>()' and 'void C<X>.K2<T, U>()' have differences in parameter names, parameter types, or return types. // partial void K2<T, U>() where T : class where U : T, IA<U> { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "K2").WithArguments("void C<X>.K2<T1, T2>()", "void C<X>.K2<T, U>()").WithLocation(33, 18), // (38,18): error CS0761: Partial method declarations of 'C<X>.A1<T>()' have inconsistent constraints for type parameter 'T' // partial void A1<T>() where T : class { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "A1").WithArguments("C<X>.A1<T>()", "T").WithLocation(38, 18)); } [Fact] public void CS0761ERR_PartialMethodInconsistentConstraints02() { var source = @"using NIA = N.IA; using NIBA = N.IB<N.IA>; using NIBAC = N.IB<N.A.IC>; using NA = N.A; namespace N { interface IA { } interface IB<T> { } class A { internal interface IC { } } partial class C { partial void M1<T>() where T : A, NIBA; partial void M2<T>() where T : NA, IB<IA>; partial void M3<T, U>() where U : NIBAC; partial void M4<T, U>() where T : U, NIA; } partial class C { partial void M1<T>() where T : N.A, IB<IA> { } partial void M2<T>() where T : A, NIBA { } partial void M3<T, U>() where U : N.IB<A.IC> { } partial void M4<T, U>() where T : NIA { } } }"; CreateCompilation(source).VerifyDiagnostics( // (25,22): error CS0761: Partial method declarations of 'C.M4<T, U>()' have inconsistent constraints for type parameter 'T' // partial void M4<T, U>() where T : NIA { } Diagnostic(ErrorCode.ERR_PartialMethodInconsistentConstraints, "M4").WithArguments("N.C.M4<T, U>()", "T").WithLocation(25, 22)); } [Fact] public void CS07ERR_PartialMethodStaticDifference() { var text = @"partial class C { static partial void M1(); partial void M1() { } static partial void M2() { } partial void M2(); }"; CreateCompilation(text).VerifyDiagnostics( // (4,18): error CS07: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M1").WithLocation(4, 18), // (5,25): error CS07: Both partial method declarations must be static or neither may be static Diagnostic(ErrorCode.ERR_PartialMethodStaticDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0764ERR_PartialMethodUnsafeDifference() { var text = @"partial class C { unsafe partial void M1(); partial void M1() { } unsafe partial void M2() { } partial void M2(); }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,18): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M1").WithLocation(4, 18), // (5,25): error CS0764: Both partial method declarations must be unsafe or neither may be unsafe Diagnostic(ErrorCode.ERR_PartialMethodUnsafeDifference, "M2").WithLocation(5, 25)); } [Fact] public void CS0766ERR_PartialMethodMustReturnVoid() { var text = @" public partial class C { partial int Part(); partial int Part() { return 1; } public static int Main() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): error CS8794: Partial method 'C.Part()' must have accessibility modifiers because it has a non-void return type. // partial int Part(); Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "Part").WithArguments("C.Part()").WithLocation(5, 17), // (6,17): error CS8794: Partial method 'C.Part()' must have accessibility modifiers because it has a non-void return type. // partial int Part() Diagnostic(ErrorCode.ERR_PartialMethodWithNonVoidReturnMustHaveAccessMods, "Part").WithArguments("C.Part()").WithLocation(6, 17)); } [Fact] public void CS0767ERR_ExplicitImplCollisionOnRefOut() { var text = @"interface IFace<T> { void Goo(ref T x); void Goo(out int x); } class A : IFace<int> { void IFace<int>.Goo(ref int x) { } void IFace<int>.Goo(out int x) { x = 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 }, //error for IFace<int, int>.Goo(ref int) new ErrorDescription { Code = (int)ErrorCode.ERR_ExplicitImplCollisionOnRefOut, Line = 1, Column = 11 } //error for IFace<int, int>.Goo(out int) ); } [Fact] public void CS0825ERR_TypeVarNotFound01() { var text = @"namespace NS { class Test { static var myStaticField; extern private var M(); void MM(ref var v) { } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (6,24): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // extern private var M(); Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (7,21): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // void MM(ref var v) { } Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (5,16): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code // static var myStaticField; Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var"), // (6,28): warning CS0626: Method, operator, or accessor 'NS.Test.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern private var M(); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("NS.Test.M()"), // (5,20): warning CS0169: The field 'NS.Test.myStaticField' is never used // static var myStaticField; Diagnostic(ErrorCode.WRN_UnreferencedField, "myStaticField").WithArguments("NS.Test.myStaticField") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] [WorkItem(22512, "https://github.com/dotnet/roslyn/issues/22512")] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public int Num // CS0625 { get; set; } static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (9,20): error CS0625: 'Str.Num': instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute // public int Num // CS0625 Diagnostic(ErrorCode.ERR_MissingStructOffset, "Num").WithArguments("TestNamespace.Str.Num").WithLocation(9, 20) ); } [Fact] [WorkItem(1032724, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032724")] public void CS0842ERR_ExplicitLayoutAndAutoImplementedProperty_Bug1032724() { var text = @" using System.Runtime.InteropServices; namespace TestNamespace { [StructLayout(LayoutKind.Explicit)] struct Str { public static int Num { get; set; } static int Main() { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS0851ERR_OverloadRefOutCtor() { var text = @"namespace TestNamespace { class MyClass { public MyClass(ref int num) { } public MyClass(out int num) { num = 1; } } }"; CreateCompilation(text).VerifyDiagnostics( // (8,17): error CS0663: 'MyClass' cannot define an overloaded constructor that differs only on parameter modifiers 'out' and 'ref' // public MyClass(out int num) Diagnostic(ErrorCode.ERR_OverloadRefKind, "MyClass").WithArguments("TestNamespace.MyClass", "constructor", "out", "ref").WithLocation(8, 17)); } [Fact] public void CS1014ERR_GetOrSetExpected() { var source = @"partial class C { public object P { partial get; set; } object Q { get { return 0; } add { } } } "; CreateCompilation(source).VerifyDiagnostics( // (3,23): error CS1014: A get, set or init accessor expected // public object P { partial get; set; } Diagnostic(ErrorCode.ERR_GetOrSetExpected, "partial").WithLocation(3, 23), // (4,34): error CS1014: A get, set or init accessor expected // object Q { get { return 0; } add { } } Diagnostic(ErrorCode.ERR_GetOrSetExpected, "add").WithLocation(4, 34)); } [Fact] public void CS1057ERR_ProtectedInStatic01() { var text = @"namespace NS { public static class B { protected static object field = null; internal protected static void M() {} } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 5, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 6, Column = 40 }); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; // TODO... } [Fact] public void CanNotDeclareProtectedPropertyInStaticClass() { const string text = @" static class B { protected static int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 24 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 28 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }); } [Fact] public void CanNotDeclareProtectedInternalPropertyInStaticClass() { const string text = @" static class B { internal static protected int X { get; set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 33 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 37 }, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic, Line = 3, Column = 42 }); } [Fact] public void CanNotDeclarePropertyWithProtectedInternalAccessorInStaticClass() { const string text = @" static class B { public static int X { get; protected internal set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_ProtectedInStatic }); } /// <summary> /// variance /// </summary> [Fact] public void CS1067ERR_PartialWrongTypeParamsVariance01() { var text = @"namespace NS { //combinations partial interface I1<in T> { } partial interface I1<out T> { } partial interface I2<in T> { } partial interface I2<T> { } partial interface I3<T> { } partial interface I3<out T> { } //no duplicate errors partial interface I4<T, U> { } partial interface I4<out T, out U> { } //prefer over CS0264 partial interface I5<S> { } partial interface I5<out T> { } //no error after CS0264 partial interface I6<R, in T> { } partial interface I6<S, out T> { } //no error since arities don't match partial interface I7<T> { } partial interface I7<in T, U> { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,23): error CS1067: Partial declarations of 'NS.I1<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I1").WithArguments("NS.I1<T>"), // (7,23): error CS1067: Partial declarations of 'NS.I2<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I2").WithArguments("NS.I2<T>"), // (10,23): error CS1067: Partial declarations of 'NS.I3<T>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I3").WithArguments("NS.I3<T>"), // (14,23): error CS1067: Partial declarations of 'NS.I4<T, U>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I4").WithArguments("NS.I4<T, U>"), // (18,23): error CS1067: Partial declarations of 'NS.I5<S>' must have the same type parameter names and variance modifiers in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParamsVariance, "I5").WithArguments("NS.I5<S>"), // (22,23): error CS0264: Partial declarations of 'NS.I6<R, T>' must have the same type parameter names in the same order Diagnostic(ErrorCode.ERR_PartialWrongTypeParams, "I6").WithArguments("NS.I6<R, T>")); } [Fact] public void CS1100ERR_BadThisParam() { var text = @"static class Test { static void ExtMethod(int i, this Goo1 c) // CS1100 { } } class Goo1 { }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (3,34): error CS1100: Method 'ExtMethod' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("ExtMethod").WithLocation(3, 34)); } [Fact] public void CS1103ERR_BadTypeforThis01() { // Note that the dev11 compiler does not report error CS0721, that C cannot be used as a parameter type. // This appears to be a shortcoming of the dev11 compiler; there is no good reason to not report the error. var compilation = CreateCompilation( @"static class C { static void M1(this Unknown u) { } static void M2(this C c) { } static void M3(this dynamic d) { } static void M4(this dynamic[] d) { } }"); compilation.VerifyDiagnostics( // (3,25): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown"), // (4,17): error CS0721: 'C': static types cannot be used as parameters Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "M2").WithArguments("C"), // (5,25): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic")); } [Fact] public void CS1103ERR_BadTypeforThis02() { CreateCompilation( @"public static class Extensions { public unsafe static char* Test(this char* charP) { return charP; } // CS1103 } ", options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadTypeforThis, "char*").WithArguments("char*").WithLocation(3, 42)); } [Fact] public void CS1105ERR_BadExtensionMeth() { var text = @"public class Extensions { public void Test<T>(this System.String s) { } //CS1105 } "; var reference = SystemCoreRef; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new List<MetadataReference> { reference }, new ErrorDescription { Code = (int)ErrorCode.ERR_BadExtensionAgg, Line = 1, Column = 14 }); } [Fact] public void CS1106ERR_BadExtensionAgg01() { var compilation = CreateCompilation( @"class A { static void M(this object o) { } } class B { static void M<T>(this object o) { } } static class C<T> { static void M(this object o) { } } static class D<T> { static void M<U>(this object o) { } } struct S { static void M(this object o) { } } struct T { static void M<U>(this object o) { } } struct U<T> { static void M(this object o) { } }"); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadExtensionAgg, "A").WithLocation(1, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(5, 7), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "C").WithLocation(9, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "D").WithLocation(13, 14), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "S").WithLocation(17, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "T").WithLocation(21, 8), Diagnostic(ErrorCode.ERR_BadExtensionAgg, "U").WithLocation(25, 8)); } [WorkItem(528256, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528256")] [Fact()] public void CS1106ERR_BadExtensionAgg02() { CreateCompilation( @"interface I { static void M(this object o); }", parseOptions: TestOptions.Regular7) .VerifyDiagnostics( // (3,17): error CS8503: The modifier 'static' is not valid for this item in C# 7. Please use language version '8.0' or greater. // static void M(this object o); Diagnostic(ErrorCode.ERR_InvalidModifierForLanguageVersion, "M").WithArguments("static", "7.0", "8.0").WithLocation(3, 17), // (1,11): error CS1106: Extension method must be defined in a non-generic static class // interface I Diagnostic(ErrorCode.ERR_BadExtensionAgg, "I").WithLocation(1, 11), // (3,17): error CS0501: 'I.M(object)' must declare a body because it is not marked abstract, extern, or partial // static void M(this object o); Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "M").WithArguments("I.M(object)").WithLocation(3, 17) ); } [Fact] public void CS1109ERR_ExtensionMethodsDecl() { var compilation = CreateCompilation( @"class A { static class C { static void M(this object o) { } } } static class B { static class C { static void M(this object o) { } } } struct S { static class C { static void M(this object o) { } } }"); compilation.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(5, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(12, 21), Diagnostic(ErrorCode.ERR_ExtensionMethodsDecl, "M").WithArguments("C").WithLocation(19, 21)); } [Fact] public void CS1110ERR_ExtensionAttrNotFound() { //Extension method cannot be declared without a reference to System.Core.dll var source = @"static class A { public static void M1(this object o) { } public static void M2(this string s, this object o) { } public static void M3(this dynamic d) { } } class B { public static void M4(this object o) { } }"; var compilation = CreateEmptyCompilation(source, new[] { TestMetadata.Net40.mscorlib }); compilation.VerifyDiagnostics( // (3,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(3, 27), // (4,27): error CS1110: Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll? Diagnostic(ErrorCode.ERR_ExtensionAttrNotFound, "this").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute").WithLocation(4, 27), // (4,42): error CS1100: Method 'M2' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M2").WithLocation(4, 42), // (5,32): error CS1103: The first parameter of an extension method cannot be of type 'dynamic' Diagnostic(ErrorCode.ERR_BadTypeforThis, "dynamic").WithArguments("dynamic").WithLocation(5, 32), // (5,32): error CS1980: Cannot define a class or member that utilizes 'dynamic' because the compiler required type 'System.Runtime.CompilerServices.DynamicAttribute' cannot be found. Are you missing a reference? Diagnostic(ErrorCode.ERR_DynamicAttributeMissing, "dynamic").WithArguments("System.Runtime.CompilerServices.DynamicAttribute").WithLocation(5, 32), // (7,7): error CS1106: Extension methods must be defined in a non-generic static class Diagnostic(ErrorCode.ERR_BadExtensionAgg, "B").WithLocation(7, 7)); } [Fact] public void CS1112ERR_ExplicitExtension() { var source = @"using System.Runtime.CompilerServices; [System.Runtime.CompilerServices.ExtensionAttribute] static class A { static void M(object o) { } } static class B { [Extension] static void M() { } [ExtensionAttribute] static void M(this object o) { } [Extension] static object P { [Extension] get { return null; } } [Extension(0)] static object F; }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (2,2): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [System.Runtime.CompilerServices.ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "System.Runtime.CompilerServices.ExtensionAttribute"), // (9,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (11,6): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [ExtensionAttribute] Diagnostic(ErrorCode.ERR_ExplicitExtension, "ExtensionAttribute"), // (13,6): error CS0592: Attribute 'Extension' is not valid on this declaration type. It is only valid on 'assembly, class, method' declarations. // [Extension] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Extension").WithArguments("Extension", "assembly, class, method"), // (16,10): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead. // [Extension] Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension"), // (19,6): error CS1729: 'System.Runtime.CompilerServices.ExtensionAttribute' does not contain a constructor that takes 1 arguments // [Extension(0)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "Extension(0)").WithArguments("System.Runtime.CompilerServices.ExtensionAttribute", "1"), // (20,19): warning CS0169: The field 'B.F' is never used // static object F; Diagnostic(ErrorCode.WRN_UnreferencedField, "F").WithArguments("B.F")); } [Fact] public void CS1509ERR_ImportNonAssembly() { //CSC /TARGET:library /reference:class1.netmodule text.CS var text = @"class Test { public static int Main() { return 1; } }"; var ref1 = AssemblyMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "NetModule.mod"); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // error CS1509: The referenced file 'NetModule.mod' is not an assembly Diagnostic(ErrorCode.ERR_ImportNonAssembly).WithArguments(@"NetModule.mod")); } [Fact] public void CS1527ERR_NoNamespacePrivate1() { var text = @"private class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 15 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate2() { var text = @"protected class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 17 } //pos = the class name ); } [Fact] public void CS1527ERR_NoNamespacePrivate3() { var text = @"protected internal class C { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoNamespacePrivate, Line = 1, Column = 26 } //pos = the class name ); } [Fact] public void CS1537ERR_DuplicateAlias1() { var text = @"using A = System; using A = System; namespace NS { using O = System.Object; using O = System.Object; }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (2,7): error CS1537: The using alias 'A' appeared previously in this namespace // using A = System; Diagnostic(ErrorCode.ERR_DuplicateAlias, "A").WithArguments("A"), // (7,11): error CS1537: The using alias 'O' appeared previously in this namespace // using O = System.Object; Diagnostic(ErrorCode.ERR_DuplicateAlias, "O").WithArguments("O"), // (1,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (2,1): info CS8019: Unnecessary using directive. // using A = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = System;"), // (6,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;"), // (7,5): info CS8019: Unnecessary using directive. // using O = System.Object; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using O = System.Object;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [WorkItem(537684, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537684")] [Fact] public void CS1537ERR_DuplicateAlias2() { var text = @"namespace namespace1 { class A { } } namespace namespace2 { class B { } } namespace NS { using ns = namespace1; using ns = namespace2; using System; class C : ns.A { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (14,11): error CS1537: The using alias 'ns' appeared previously in this namespace // using ns = namespace2; Diagnostic(ErrorCode.ERR_DuplicateAlias, "ns").WithArguments("ns"), // (14,5): info CS8019: Unnecessary using directive. // using ns = namespace2; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ns = namespace2;"), // (15,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("C").Single() as NamedTypeSymbol; var b = type1.BaseType(); } [Fact] public void CS1537ERR_DuplicateAlias3() { var text = @"using X = System; using X = ABC.X<int>;"; CreateCompilation(text).VerifyDiagnostics( // (2,7): error CS1537: The using alias 'X' appeared previously in this namespace // using X = ABC.X<int>; Diagnostic(ErrorCode.ERR_DuplicateAlias, "X").WithArguments("X"), // (1,1): info CS8019: Unnecessary using directive. // using X = System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = System;"), // (2,1): info CS8019: Unnecessary using directive. // using X = ABC.X<int>; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using X = ABC.X<int>;")); } [WorkItem(539125, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539125")] [Fact] public void CS1542ERR_AddModuleAssembly() { //CSC /addmodule:cs1542.dll /TARGET:library text1.cs var text = @"public class Goo : IGoo { public void M0() { } }"; var ref1 = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.CorLibrary.NoMsCorLibRef).GetReference(display: "NoMsCorLibRef.mod"); CreateCompilation(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1542: 'NoMsCorLibRef.mod' cannot be added to this assembly because it already is an assembly Diagnostic(ErrorCode.ERR_AddModuleAssembly).WithArguments(@"NoMsCorLibRef.mod"), // (1,20): error CS0246: The type or namespace name 'IGoo' could not be found (are you missing a using directive or an assembly reference?) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IGoo").WithArguments("IGoo")); } [Fact, WorkItem(544910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544910")] public void CS1599ERR_MethodReturnCantBeRefAny() { var text = @" using System; interface I { ArgIterator M(); // 1599 } class C { public delegate TypedReference Test1(); // 1599 public RuntimeArgumentHandle Test2() // 1599 { return default(RuntimeArgumentHandle); } // The native compiler does not catch this one; Roslyn does. public static ArgIterator operator +(C c1, C c2) // 1599 { return default(ArgIterator); } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (5,5): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.ArgIterator' // ArgIterator M(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (11,12): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.RuntimeArgumentHandle' // public RuntimeArgumentHandle Test2() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle"), // (17,19): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.ArgIterator' // public static ArgIterator operator +(C c1, C c2) // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator"), // (9,21): error CS1599: The return type of a method, delegate, or function pointer cannot be 'System.TypedReference' // public delegate TypedReference Test1(); // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference") ); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionReturnCantBeRefAny() { var text = @" class C { public void Goo() { System.TypedReference local1() // 1599 { return default; } local1(); System.RuntimeArgumentHandle local2() // 1599 { return default; } local2(); System.ArgIterator local3() // 1599 { return default; } local3(); } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (6,9): error CS1599: The return type of a method, delegate, or function pointer cannot be 'TypedReference' // System.TypedReference local1() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.TypedReference").WithArguments("System.TypedReference").WithLocation(6, 9), // (12,9): error CS1599: The return type of a method, delegate, or function pointer cannot be 'RuntimeArgumentHandle' // System.RuntimeArgumentHandle local2() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(12, 9), // (18,9): error CS1599: The return type of a method, delegate, or function pointer cannot be 'ArgIterator' // System.ArgIterator local3() // 1599 Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "System.ArgIterator").WithArguments("System.ArgIterator").WithLocation(18, 9)); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionReturnCanBeSpan() { var text = @" using System; class C { static void M() { byte[] bytes = new byte[1]; Span<byte> local1() { return new Span<byte>(bytes); } Span<byte> res = local1(); } } "; CreateCompilationWithMscorlibAndSpanSrc(text).VerifyDiagnostics(); } [Fact, WorkItem(544910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544910")] public void CS1601ERR_MethodArgCantBeRefAny() { // We've changed the text of the error message from // CS1601: Method or delegate parameter cannot be of type 'ref System.TypedReference' // to // CS1601: Cannot make reference to variable of type 'System.TypedReference' // because we use this error message at both the call site and the declaration. // The new wording makes sense in both uses; the former only makes sense at // the declaration site. var text = @" using System; class MyClass { delegate void D(ref TypedReference t1); // CS1601 public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 { var x = __makeref(r3); // CS1601 } public void Test2(out ArgIterator t4) // CS1601 { t4 = default(ArgIterator); } MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (6,23): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // public void Test1(ref TypedReference t2, RuntimeArgumentHandle r3) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t2").WithArguments("System.TypedReference"), // (11,23): error CS1601: Cannot make reference to variable of type 'System.ArgIterator' // public void Test2(out ArgIterator t4) // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out ArgIterator t4").WithArguments("System.ArgIterator"), // (16,13): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // MyClass(ref RuntimeArgumentHandle r5) {} // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref RuntimeArgumentHandle r5").WithArguments("System.RuntimeArgumentHandle"), // (5,21): error CS1601: Cannot make reference to variable of type 'System.TypedReference' // delegate void D(ref TypedReference t1); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref TypedReference t1").WithArguments("System.TypedReference"), // (8,17): error CS1601: Cannot make reference to variable of type 'System.RuntimeArgumentHandle' // var x = __makeref(r3); // CS1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "__makeref(r3)").WithArguments("System.RuntimeArgumentHandle") ); } [Fact, WorkItem(27463, "https://github.com/dotnet/roslyn/issues/27463")] public void CS1599ERR_LocalFunctionParamCantBeRefAny() { var text = @" class C { public void Goo() { { System.TypedReference _arg = default; void local1(ref System.TypedReference tr) { } // 1601 local1(ref _arg); void local2(in System.TypedReference tr) { } // 1601 local2(in _arg); void local3(out System.TypedReference tr) // 1601 { tr = default; } local3(out _arg); } { System.ArgIterator _arg = default; void local1(ref System.ArgIterator ai) { } // 1601 local1(ref _arg); void local2(in System.ArgIterator ai) { } // 1601 local2(in _arg); void local3(out System.ArgIterator ai) // 1601 { ai = default; } local3(out _arg); } { System.RuntimeArgumentHandle _arg = default; void local1(ref System.RuntimeArgumentHandle ah) { } // 1601 local1(ref _arg); void local2(in System.RuntimeArgumentHandle ah) { } // 1601 local2(in _arg); void local3(out System.RuntimeArgumentHandle ah) // 1601 { ah = default; } local3(out _arg); } } } "; CreateCompilationWithMscorlib46(text).VerifyDiagnostics( // (8,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local1(ref System.TypedReference tr) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(8, 25), // (11,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local2(in System.TypedReference tr) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(11, 25), // (14,25): error CS1601: Cannot make reference to variable of type 'TypedReference' // void local3(out System.TypedReference tr) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.TypedReference tr").WithArguments("System.TypedReference").WithLocation(14, 25), // (23,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local1(ref System.ArgIterator ai) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(23, 25), // (26,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local2(in System.ArgIterator ai) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(26, 25), // (29,25): error CS1601: Cannot make reference to variable of type 'ArgIterator' // void local3(out System.ArgIterator ai) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.ArgIterator ai").WithArguments("System.ArgIterator").WithLocation(29, 25), // (38,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local1(ref System.RuntimeArgumentHandle ah) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "ref System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(38, 25), // (41,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local2(in System.RuntimeArgumentHandle ah) { } // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "in System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(41, 25), // (44,25): error CS1601: Cannot make reference to variable of type 'RuntimeArgumentHandle' // void local3(out System.RuntimeArgumentHandle ah) // 1601 Diagnostic(ErrorCode.ERR_MethodArgCantBeRefAny, "out System.RuntimeArgumentHandle ah").WithArguments("System.RuntimeArgumentHandle").WithLocation(44, 25)); } [WorkItem(542003, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542003")] [Fact] public void CS1608ERR_CantUseRequiredAttribute() { var text = @"using System.Runtime.CompilerServices; [RequiredAttribute(typeof(object))] class ClassMain { }"; CreateCompilation(text).VerifyDiagnostics( // (3,2): error CS1608: The Required attribute is not permitted on C# types // [RequiredAttribute(typeof(object))] Diagnostic(ErrorCode.ERR_CantUseRequiredAttribute, "RequiredAttribute").WithLocation(3, 2)); } [Fact] public void CS1614ERR_AmbiguousAttribute() { var text = @"using System; class A : Attribute { } class AAttribute : Attribute { } [A][@A][AAttribute] class C { } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbiguousAttribute, Line = 4, Column = 2 }); } [Fact] public void CS0214ERR_RequiredInUnsafeContext() { var text = @"struct C { public fixed int ab[10]; // CS0214 } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseDll); // (3,25): error CS0214: Pointers and fixed size buffers may only be used in an unsafe context // public fixed string ab[10]; // CS0214 Diagnostic(ErrorCode.ERR_UnsafeNeeded, "ab[10]"); } [Fact] public void CS1642ERR_FixedNotInStruct() { var text = @"unsafe class C { fixed int a[10]; // CS1642 }"; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,15): error CS1642: Fixed size buffer fields may only be members of structs // fixed int a[10]; // CS1642 Diagnostic(ErrorCode.ERR_FixedNotInStruct, "a")); } [Fact] public void CS1663ERR_IllegalFixedType() { var text = @"unsafe struct C { fixed string ab[10]; // CS1663 }"; var comp = CreateCompilation(text, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (3,11): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // fixed string ab[10]; // CS1663 Diagnostic(ErrorCode.ERR_IllegalFixedType, "string")); } [WorkItem(545353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545353")] [Fact] public void CS1664ERR_FixedOverflow() { // set Allow unsafe code = true var text = @"public unsafe struct C { unsafe private fixed long test_1[1073741825]; }"; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,38): error CS1664: Fixed size buffer of length '1073741825' and type 'long' is too big // unsafe private fixed long test_1[1073741825]; Diagnostic(ErrorCode.ERR_FixedOverflow, "1073741825").WithArguments("1073741825", "long")); } [WorkItem(545353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545353")] [Fact] public void CS1665ERR_InvalidFixedArraySize() { var text = @"unsafe struct S { public unsafe fixed int A[0]; // CS1665 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS1665: Fixed size buffers must have a length greater than zero // public unsafe fixed int A[0]; // CS1665 Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "0")); } [WorkItem(546922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546922")] [Fact] public void CS1665ERR_InvalidFixedArraySizeNegative() { var text = @"unsafe struct S { public unsafe fixed int A[-1]; // CS1665 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_InvalidFixedArraySize, "-1")); } [Fact()] public void CS0443ERR_InvalidFixedArraySizeNotSpecified() { var text = @"unsafe struct S { public unsafe fixed int A[]; // CS0443 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,31): error CS0443: Syntax error; value expected // public unsafe fixed int A[]; // CS0443 Diagnostic(ErrorCode.ERR_ValueExpected, "]")); } [Fact] public void CS1003ERR_InvalidFixedArrayMultipleDimensions() { var text = @"unsafe struct S { public unsafe fixed int A[2,2]; // CS1003,CS1001 public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,33): error CS1002: ; expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_SemicolonExpected, "["), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,34): error CS1001: Identifier expected // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_IdentifierExpected, "2"), // (4,36): error CS1519: Invalid token ';' in class, record, struct, or interface member declaration // public unsafe fixed int B[2][2]; // CS1003,CS1001,CS1519 Diagnostic(ErrorCode.ERR_InvalidMemberDecl, ";").WithArguments(";"), // (3,30): error CS7092: A fixed buffer may only have one dimension. // public unsafe fixed int A[2,2]; // CS1003,CS1001 Diagnostic(ErrorCode.ERR_FixedBufferTooManyDimensions, "[2,2]")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested() { var text = @"unsafe struct S { unsafe class Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; //Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferInner[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferInner")); } [Fact] public void CS1642ERR_InvalidFixedBufferNested_2() { var text = @"unsafe class S { unsafe struct Err_OnlyOnInstanceInStructure { public fixed bool _bufferInner[10]; // Valid } public fixed bool _bufferOuter[10]; // error CS1642: Fixed size buffer fields may only be members of structs } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (5,31): error CS1642: Fixed size buffer fields may only be members of structs // public fixed bool _bufferOuter[10]; //Valid Diagnostic(ErrorCode.ERR_FixedNotInStruct, "_bufferOuter")); } [Fact] public void CS0133ERR_InvalidFixedBufferCountFromField() { var text = @"unsafe struct s { public static int var1 = 10; public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (4,34): error CS0133: The expression being assigned to 's._Type3' must be constant // public fixed bool _Type3[var1]; // error CS0133: The expression being assigned to '<Type>' must be constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "var1").WithArguments("s._Type3")); } [Fact] public void CS1663ERR_InvalidFixedBufferUsingGenericType() { var text = @"unsafe struct Err_FixedBufferDeclarationUsingGeneric<t> { public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed t _Type1[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "t")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypes() { var text = @"unsafe struct s { public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) public fixed int _Type2[true]; // error CS00029 public fixed int _Type3[""true""]; // error CS00029 public fixed int _Type4[System.Convert.ToInt32(@""1"")]; // error CS0133 } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,33): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // public fixed int _Type1[1.2]; // error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1.2").WithArguments("double", "int"), // (4,33): error CS0029: Cannot implicitly convert type 'bool' to 'int' // public fixed int _Type2[true]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, "true").WithArguments("bool", "int"), // (5,33): error CS0029: Cannot implicitly convert type 'string' to 'int' // public fixed int _Type3["true"]; // error CS00029 Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""true""").WithArguments("string", "int"), // (6,33): error CS0133: The expression being assigned to 's._Type4' must be constant // public fixed int _Type4[System.Convert.ToInt32(@"1")]; // error CS0133 Diagnostic(ErrorCode.ERR_NotConstantExpression, @"System.Convert.ToInt32(@""1"")").WithArguments("s._Type4")); } [Fact] public void CS0029ERR_InvalidFixedBufferNonValidTypesUserDefinedTypes() { var text = @"unsafe struct s { public fixed goo _bufferGoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double } struct goo { public int ABC; } class bar { public bool ABC = true; } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (3,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed goo _bufferGoo[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "goo"), // (4,22): error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double // public fixed bar _bufferBar[10]; // error CS1663: Fixed size buffer type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double Diagnostic(ErrorCode.ERR_IllegalFixedType, "bar"), // (9,20): warning CS0649: Field 'goo.ABC' is never assigned to, and will always have its default value 0 // public int ABC; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "ABC").WithArguments("goo.ABC", "0")); } [Fact] public void C1666ERR_InvalidFixedBufferInUnfixedContext() { var text = @" unsafe struct s { private fixed ushort _e_res[4]; void Error_UsingFixedBuffersWithThis() { ushort c = this._e_res; } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,24): error CS1666: You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement. // ushort c = this._e_res; Diagnostic(ErrorCode.ERR_FixedBufferNotFixed, "this._e_res")); } [Fact] public void CS0029ERR_InvalidFixedBufferUsageInLocal() { //Some additional errors generated but the key ones from native are here. var text = @"unsafe struct s { //Use as local rather than field with unsafe on method // Incorrect usage of fixed buffers in method bodies try to use as a local static unsafe void Error_UseAsLocal() { //Invalid In Use as Local fixed bool _buffer[2]; // error CS1001: Identifier expected } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,15): error CS1003: Syntax error, '(' expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_SyntaxError, "bool").WithArguments("(", "bool"), // (8,27): error CS0650: Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type. // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CStyleArray, "[2]"), // (8,28): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression) // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_ArraySizeInDeclaration, "2"), // (8,30): error CS1026: ) expected // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_CloseParenExpected, ";"), // (8,30): warning CS0642: Possible mistaken empty statement // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.WRN_PossibleMistakenNullStatement, ";"), // (8,20): error CS0209: The type of a local declared in a fixed statement must be a pointer type // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_BadFixedInitType, "_buffer[2]"), // (8,20): error CS0210: You must provide an initializer in a fixed or using statement declaration // fixed bool _buffer[2]; // error CS1001: Identifier expected Diagnostic(ErrorCode.ERR_FixedMustInit, "_buffer[2]")); } [Fact()] public void CS1667ERR_AttributeNotOnAccessor() { var text = @"using System; public class C { private int i; public int ObsoleteProperty { [Obsolete] // CS1667 get { return i; } [System.Diagnostics.Conditional(""Bernard"")] set { i = value; } } public static void Main() { } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (10,10): error CS1667: Attribute 'System.Diagnostics.Conditional' is not valid on property or event accessors. It is only valid on 'class, method' declarations. // [System.Diagnostics.Conditional("Bernard")] Diagnostic(ErrorCode.ERR_AttributeNotOnAccessor, "System.Diagnostics.Conditional").WithArguments("System.Diagnostics.Conditional", "class, method") ); } [Fact] public void CS1689ERR_ConditionalOnNonAttributeClass() { var text = @"[System.Diagnostics.Conditional(""A"")] // CS1689 class MyClass {} "; CreateCompilation(text).VerifyDiagnostics( // (1,2): error CS1689: Attribute 'System.Diagnostics.Conditional' is only valid on methods or attribute classes // [System.Diagnostics.Conditional("A")] // CS1689 Diagnostic(ErrorCode.ERR_ConditionalOnNonAttributeClass, @"System.Diagnostics.Conditional(""A"")").WithArguments("System.Diagnostics.Conditional").WithLocation(1, 2)); } // CS17ERR_DuplicateImport: See ReferenceManagerTests.CS17ERR_DuplicateImport // CS1704ERR_DuplicateImportSimple: See ReferenceManagerTests.CS1704ERR_DuplicateImportSimple [Fact(Skip = "530901"), WorkItem(530901, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530901")] public void CS1705ERR_AssemblyMatchBadVersion() { // compile with: /target:library /out:c:\\cs1705.dll /keyfile:mykey.snk var text1 = @"[assembly:System.Reflection.AssemblyVersion(""1.0"")] public class A { public void M1() {} public class N1 {} public void M2() {} public class N2 {} } public class C1 {} public class C2 {} "; var tree1 = SyntaxFactory.ParseCompilationUnit(text1); // compile with: /target:library /out:cs1705.dll /keyfile:mykey.snk var text2 = @"using System.Reflection; [assembly:AssemblyVersion(""2.0"")] public class A { public void M2() {} public class N2 {} public void M1() {} public class N1 {} } public class C2 {} public class C1 {} "; var tree2 = SyntaxFactory.ParseCompilationUnit(text2); // compile with: /target:library /r:A2=c:\\CS1705.dll /r:A1=CS1705.dll var text3 = @"extern alias A1; extern alias A2; using a1 = A1::A; using a2 = A2::A; using n1 = A1::A.N1; using n2 = A2::A.N2; public class Ref { public static a1 A1() { return new a1(); } public static a2 A2() { return new a2(); } public static A1::C1 M1() { return new A1::C1(); } public static A2::C2 M2() { return new A2::C2(); } public static n1 N1() { return new a1.N1(); } public static n2 N2() { return new a2.N2(); } } "; var tree3 = SyntaxFactory.ParseCompilationUnit(text3); // compile with: /reference:c:\\CS1705.dll /reference:CS1705_c.dll var text = @"class Tester { static void Main() { Ref.A1().M1(); Ref.A2().M2(); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AssemblyMatchBadVersion, Line = 2, Column = 12 }); } [Fact] public void CS1715ERR_CantChangeTypeOnOverride() { var text = @"abstract public class Base { abstract public int myProperty { get; set; } } public class Derived : Base { int myField; public override double myProperty // CS1715 { get { return myField; } set { myField= 1; } } public static void Main() { } } "; // The set accessor has the wrong parameter type so is not implemented. // The override get accessor has the right signature (no parameters) so is implemented, though with the wrong return type. CreateCompilation(text).VerifyDiagnostics( // (10,14): error CS0534: 'Derived' does not implement inherited abstract member 'Base.myProperty.set' // public class Derived : Base Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "Derived").WithArguments("Derived", "Base.myProperty.set").WithLocation(10, 14), // (13,28): error CS1715: 'Derived.myProperty': type must be 'int' to match overridden member 'Base.myProperty' // public override double myProperty // CS1715 Diagnostic(ErrorCode.ERR_CantChangeTypeOnOverride, "myProperty").WithArguments("Derived.myProperty", "Base.myProperty", "int").WithLocation(13, 28) ); } [Fact] public void CS1716ERR_DoNotUseFixedBufferAttr() { var text = @" using System.Runtime.CompilerServices; public struct UnsafeStruct { [FixedBuffer(typeof(int), 4)] // CS1716 unsafe public int aField; } public class TestUnsafe { static void Main() { } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (6,6): error CS1716: Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead. // [FixedBuffer(typeof(int), 4)] // CS1716 Diagnostic(ErrorCode.ERR_DoNotUseFixedBufferAttr, "FixedBuffer").WithLocation(6, 6)); } [Fact] public void CS1721ERR_NoMultipleInheritance01() { var text = @"namespace NS { public class A { } public class B { } public class C : B { } public class MyClass : A, A { } // CS1721 public class MyClass2 : A, B { } // CS1721 public class MyClass3 : C, A { } // CS1721 } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 6, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 7, Column = 32 }, new ErrorDescription { Code = (int)ErrorCode.ERR_NoMultipleInheritance, Line = 8, Column = 32 }); } [Fact] public void CS1722ERR_BaseClassMustBeFirst01() { var text = @"namespace NS { public class A { } interface I { } interface IGoo<T> : I { } public class MyClass : I, A { } // CS1722 public class MyClass2 : A, I { } // OK class Test { class C : IGoo<int>, A , I { } // CS1722 } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 7, Column = 31 }, new ErrorDescription { Code = (int)ErrorCode.ERR_BaseClassMustBeFirst, Line = 12, Column = 30 }); } [Fact(), WorkItem(530393, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530393")] public void CS1724ERR_InvalidDefaultCharSetValue() { var text = @" using System.Runtime.InteropServices; [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 class C { [DllImport(""F.Dll"")] extern static void FW1Named(); static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,34): error CS0591: Invalid value for argument to 'DefaultCharSetAttribute' attribute // [module: DefaultCharSetAttribute((CharSet)42)] // CS1724 Diagnostic(ErrorCode.ERR_InvalidAttributeArgument, "(CharSet)42").WithArguments("DefaultCharSetAttribute") ); } [Fact, WorkItem(1116455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116455")] public void CS1725ERR_FriendAssemblyBadArgs() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""Test, Version=*"")] // ok [assembly: InternalsVisibleTo(""Test, PublicKeyToken=*"")] // ok [assembly: InternalsVisibleTo(""Test, Culture=*"")] // ok [assembly: InternalsVisibleTo(""Test, Retargetable=*"")] // ok [assembly: InternalsVisibleTo(""Test, ContentType=*"")] // ok [assembly: InternalsVisibleTo(""Test, Version=."")] // ok [assembly: InternalsVisibleTo(""Test, Version=.."")] // ok [assembly: InternalsVisibleTo(""Test, Version=..."")] // ok [assembly: InternalsVisibleTo(""Test, Version=1"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, Version=1.1.1.*"")] // error [assembly: InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")] // error [assembly: InternalsVisibleTo(""Test, CuLTure=EN"")] // error [assembly: InternalsVisibleTo(""Test, PublicKeyToken=null"")] // ok "; // Tested against Dev12 CreateCompilation(text).VerifyDiagnostics( // (12,12): error CS1725: Friend assembly reference 'Test, Version=1' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1"")").WithArguments("Test, Version=1").WithLocation(12, 12), // (13,12): error CS1725: Friend assembly reference 'Test, Version=1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.*"")").WithArguments("Test, Version=1.*").WithLocation(13, 12), // (14,12): error CS1725: Friend assembly reference 'Test, Version=1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.*"")").WithArguments("Test, Version=1.1.*").WithLocation(14, 12), // (15,12): error CS1725: Friend assembly reference 'Test, Version=1.1.1.*' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, Version=1.1.1.*"")").WithArguments("Test, Version=1.1.1.*").WithLocation(15, 12), // (16,12): error CS1725: Friend assembly reference 'Test, ProcessorArchitecture=MSIL' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, ProcessorArchitecture=MSIL"")").WithArguments("Test, ProcessorArchitecture=MSIL").WithLocation(16, 12), // (17,12): error CS1725: Friend assembly reference 'Test, CuLTure=EN' is invalid. InternalsVisibleTo declarations cannot have a version, culture, public key token, or processor architecture specified. Diagnostic(ErrorCode.ERR_FriendAssemblyBadArgs, @"InternalsVisibleTo(""Test, CuLTure=EN"")").WithArguments("Test, CuLTure=EN").WithLocation(17, 12)); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant01() { var text = @"class A { static int Age; public void Goo(int Para1 = Age) { } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (4,33): error CS1736: Default parameter value for 'Para1' must be a compile-time constant // public void Goo(int Para1 = Age) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "Age").WithArguments("Para1"), // (3,16): warning CS0169: The field 'A.Age' is never used // static int Age; Diagnostic(ErrorCode.WRN_UnreferencedField, "Age").WithArguments("A.Age") ); } [Fact] public void CS1736ERR_DefaultValueMustBeConstant02() { var source = @"class C { object this[object x, object y = new C()] { get { return null; } set { } } }"; CreateCompilation(source).VerifyDiagnostics( // (3,38): error CS1736: Default parameter value for 'y' must be a compile-time constant Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new C()").WithArguments("y").WithLocation(3, 38)); } [Fact, WorkItem(542401, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542401")] public void CS1736ERR_DefaultValueMustBeConstant_1() { var text = @" class NamedExample { static int y = 1; static void Main(string[] args) { } int CalculateBMI(int weight, int height = y) { return (weight * 7) / (height * height); } } "; CreateCompilation(text).VerifyDiagnostics( // (9,47): error CS1736: Default parameter value for 'height' must be a compile-time constant // int CalculateBMI(int weight, int height = y) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "y").WithArguments("height"), // (4,16): warning CS0414: The field 'NamedExample.y' is assigned but its value is never used // static int y = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "y").WithArguments("NamedExample.y") ); } [Fact] public void CS1737ERR_DefaultValueBeforeRequiredValue() { var text = @"class A { public void Goo(int Para1 = 1, int Para2) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1737, Line = 3, Column = 45 }); } [Fact] public void CS1741ERR_RefOutDefaultValue() { var text = @"class A { public void Goo(ref int Para1 = 1) { } public void Goo1(out int Para2 = 1) { Para2 = 2; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1741, Line = 3, Column = 21 }, new ErrorDescription { Code = 1741, Line = 5, Column = 22 }); } [Fact] public void CS17ERR_DefaultValueForExtensionParameter() { var text = @"static class C { static void M1(object o = null) { } static void M2(this object o = null) { } static void M3(object o, this int i = 0) { } }"; var compilation = CreateCompilation(text); compilation.VerifyDiagnostics( // (4,20): error CS17: Cannot specify a default value for the 'this' parameter Diagnostic(ErrorCode.ERR_DefaultValueForExtensionParameter, "this").WithLocation(4, 20), // (5,30): error CS1100: Method 'M3' has a parameter modifier 'this' which is not on the first parameter Diagnostic(ErrorCode.ERR_BadThisParam, "this").WithArguments("M3").WithLocation(5, 30)); } [Fact] public void CS1745ERR_DefaultValueUsedWithAttributes() { var text = @" using System.Runtime.InteropServices; class A { public void goo([OptionalAttribute]int p = 1) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,22): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void goo([OptionalAttribute]int p = 1) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "OptionalAttribute") ); } [Fact] public void CS1747ERR_NoPIAAssemblyMissingAttribute() { //csc program.cs /l:"C:\MissingPIAAttributes.dll var text = @"public class Test { static int Main(string[] args) { return 1; } }"; var ref1 = TestReferences.SymbolsTests.NoPia.Microsoft.VisualStudio.MissingPIAAttributes.WithEmbedInteropTypes(true); CreateCompilation(text, references: new[] { ref1 }).VerifyDiagnostics( // error CS1747: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing the 'System.Runtime.InteropServices.GuidAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttribute).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.GuidAttribute").WithLocation(1, 1), // error CS1759: Cannot embed interop types from assembly 'MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because it is missing either the 'System.Runtime.InteropServices.ImportedFromTypeLibAttribute' attribute or the 'System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute' attribute. Diagnostic(ErrorCode.ERR_NoPIAAssemblyMissingAttributes).WithArguments("MissingPIAAttribute, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "System.Runtime.InteropServices.ImportedFromTypeLibAttribute", "System.Runtime.InteropServices.PrimaryInteropAssemblyAttribute").WithLocation(1, 1)); } [WorkItem(620366, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620366")] [Fact] public void CS1748ERR_NoCanonicalView() { var textdll = @" using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTest"")] [assembly: Guid(""A55E0B17-2558-447D-B786-84682CBEF136"")] [assembly: BestFitMapping(false)] [ComImport, Guid(""E245C65D-2448-447A-B786-64682CBEF133"")] [TypeIdentifier(""E245C65D-2448-447A-B786-64682CBEF133"", ""IMyInterface"")] public interface IMyInterface { void Method(int n); } public delegate void DelegateWithInterface(IMyInterface value); public delegate void DelegateWithInterfaceArray(IMyInterface[] ary); public delegate IMyInterface DelegateRetInterface(); public delegate DelegateRetInterface DelegateRetDelegate(DelegateRetInterface d); "; var text = @" class Test { static void Main() { } public static void MyDelegate02(IMyInterface[] ary) { } } "; var comp1 = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp1); CreateCompilation(text, references: new MetadataReference[] { ref1 }).VerifyDiagnostics( // (77): error CS0246: The type or namespace name 'IMyInterface' could not be found (are you missing a using directive or an assembly reference?) // public static void MyDelegate02(IMyInterface[] ary) { } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IMyInterface").WithArguments("IMyInterface") ); } [Fact] public void CS1750ERR_NoConversionForDefaultParam() { var text = @"public class Generator { public void Show<T>(string msg = ""Number"", T value = null) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = 1750, Line = 3, Column = 50 }); } [Fact] public void CS1751ERR_DefaultValueForParamsParameter() { // The native compiler only produces one error here -- that // the default value on "params" is illegal. However it // seems reasonable to produce one error for each bad param. var text = @"class MyClass { public void M7(int i = null, params string[] values = ""test"") { } static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // 'i': A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'int' new ErrorDescription { Code = 1750, Line = 3, Column = 24 }, // 'params': error CS1751: Cannot specify a default value for a parameter array new ErrorDescription { Code = 1751, Line = 3, Column = 34 }); } [ConditionalFact(typeof(DesktopOnly))] public void CS1754ERR_NoPIANestedType() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyClass { public struct NestedClass { public string Name; } } } "; var text = @"public class Test { public static void Main() { var S = new NS.MyClass.NestedClass(); System.Console.Write(S); } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_NoPIANestedType, "NestedClass").WithArguments("NS.MyClass.NestedClass")); } [Fact()] public void CS1755ERR_InvalidTypeIdentifierConstructor() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { [TypeIdentifier(""Goo2"", ""Bar2"")] public delegate void MyDel(); } "; var text = @" public class Test { event NS.MyDel e; public static void Main() { } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // (4,14): error CS0234: The type or namespace name 'MyDel' does not exist in the namespace 'NS' (are you missing an assembly reference?) // event NS.MyDel e; Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "MyDel").WithArguments("MyDel", "NS"), // (4,20): warning CS0067: The event 'Test.e' is never used // event NS.MyDel e; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "e").WithArguments("Test.e")); //var comp1 = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(new List<string>() { text }, new List<MetadataReference>() { ref1 }, // new ErrorDescription { Code = 1755, Line = 4, Column = 14 }); } [ConditionalFact(typeof(DesktopOnly))] public void CS1757ERR_InteropStructContainsMethods() { var textdll = @"using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace NS { public struct MyStruct { private int _age; public string Name; } } "; var text = @"public class Test { public static void Main() { NS.MyStruct S = new NS.MyStruct(); System.Console.Write(S); } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); var comp1 = CreateCompilation(text, new[] { ref1 }); comp1.VerifyEmitDiagnostics( // (5,24): error CS1757: Embedded interop struct 'NS.MyStruct' can contain only public instance fields. // NS.MyStruct S = new NS.MyStruct(); Diagnostic(ErrorCode.ERR_InteropStructContainsMethods, "new NS.MyStruct()").WithArguments("NS.MyStruct")); } [Fact] public void CS1754ERR_NoPIANestedType_2() { //vbc /t:library PIA.vb //csc /l:PIA.dll Program.cs var textdll = @"Imports System.Runtime.InteropServices <Assembly: ImportedFromTypeLib(""GeneralPIA.dll"")> <Assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedClass Class InnerClass End Class End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedStructure Structure InnerStructure End Structure End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedEnum Enum InnerEnum Value1 End Enum End Interface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Public Interface INestedDelegate Delegate Sub InnerDelegate() End Interface Public Structure NestedInterface <Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")> <ComImport()> Interface InnerInterface End Interface End Structure Public Structure NestedClass Class InnerClass End Class End Structure Public Structure NestedStructure Structure InnerStructure End Structure End Structure Public Structure NestedEnum Enum InnerEnum Value1 End Enum End Structure Public Structure NestedDelegate Delegate Sub InnerDelegate() End Structure"; var text = @"public class Program { public static void Main() { INestedInterface.InnerInterface s1 = null; INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); INestedDelegate.InnerDelegate s5 = null; } }"; var vbcomp = VisualBasic.VisualBasicCompilation.Create( "Test", new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(textdll) }, new[] { MscorlibRef_v4_0_30316_17626 }, new VisualBasic.VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var ref1 = vbcomp.EmitToImageReference(embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( // (5,26): error CS1754: Type 'INestedInterface.InnerInterface' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerInterface").WithArguments("INestedInterface.InnerInterface"), // (6,26): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (6,71): error CS1754: Type 'INestedStructure.InnerStructure' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerStructure").WithArguments("INestedStructure.InnerStructure"), // (7,21): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (7,56): error CS1754: Type 'INestedEnum.InnerEnum' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerEnum").WithArguments("INestedEnum.InnerEnum"), // (8,25): error CS1754: Type 'INestedDelegate.InnerDelegate' cannot be embedded because it is a nested type. Consider setting the 'Embed Interop Types' property to false. // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.ERR_NoPIANestedType, "InnerDelegate").WithArguments("INestedDelegate.InnerDelegate"), // (5,41): warning CS0219: The variable 's1' is assigned but its value is never used // INestedInterface.InnerInterface s1 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s1").WithArguments("s1"), // (6,41): warning CS0219: The variable 's3' is assigned but its value is never used // INestedStructure.InnerStructure s3 = default(INestedStructure.InnerStructure); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s3").WithArguments("s3"), // (71): warning CS0219: The variable 's4' is assigned but its value is never used // INestedEnum.InnerEnum s4 = default(INestedEnum.InnerEnum); Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s4").WithArguments("s4"), // (8,39): warning CS0219: The variable 's5' is assigned but its value is never used // INestedDelegate.InnerDelegate s5 = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s5").WithArguments("s5")); } [Fact] public void CS17ERR_NotNullRefDefaultParameter() { var text = @" public static class ErrorCode { // We do not allow constant conversions from string to object in a default parameter initializer static void M1(object x = ""hello"") {} // We do not allow boxing conversions to object in a default parameter initializer static void M2(System.ValueType y = 123) {} }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, // (5,25): error CS17: 'x' is of type 'object'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 5, Column = 25 }, // (75): error CS17: 'y' is of type 'System.ValueType'. A default parameter value of a reference type other than string can only be initialized with null new ErrorDescription { Code = 1763, Line = 7, Column = 35 }); } [WorkItem(619266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619266")] [Fact(Skip = "619266")] public void CS1768ERR_GenericsUsedInNoPIAType() { // add dll and make it embed var textdll = @"using System; using System.Collections.Generic; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""NoPiaTestLib"")] [assembly: Guid(""A7721B07-2448-447A-BA36-64682CBEF136"")] namespace ClassLibrary3 { [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed5"")] public interface IGoo { IBar<string> goo(); } [ComImport, Guid(""b2496f7a-5d40-4abe-ad14-462f257a8ed6"")] public interface IBar<T> { List<IGoo> GetList(); } } "; var text = @" using System.Collections.Generic; using ClassLibrary3; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { IGoo x = (IGoo)new object(); } } class goo : IBar<string>, IGoo { public List<string> GetList() { throw new NotImplementedException(); } List<IGoo> IBar<string>.GetList() { throw new NotImplementedException(); } } } "; var comp = CreateCompilation(textdll); var ref1 = new CSharpCompilationReference(comp, embedInteropTypes: true); CreateCompilation(text, new[] { ref1 }).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_GenericsUsedInNoPIAType)); } [Fact, WorkItem(6186, "https://github.com/dotnet/roslyn/issues/6186")] public void CS1770ERR_NoConversionForNubDefaultParam() { var text = @"using System; class MyClass { public enum E { None } // No error: public void Goo1(int? x = default(int)) { } public void Goo2(E? x = default(E)) { } public void Goo3(DateTime? x = default(DateTime?)) { } public void Goo4(DateTime? x = new DateTime?()) { } // Error: public void Goo11(DateTime? x = default(DateTime)) { } public void Goo12(DateTime? x = new DateTime()) { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (13,33): error CS1770: A value of type 'DateTime' cannot be used as default parameter for nullable parameter 'x' because 'DateTime' is not a simple type // public void Goo11(DateTime? x = default(DateTime)) { } Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("System.DateTime", "x").WithLocation(13, 33), // (14,33): error CS1770: A value of type 'DateTime' cannot be used as default parameter for nullable parameter 'x' because 'DateTime' is not a simple type // public void Goo12(DateTime? x = new DateTime()) { } Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("System.DateTime", "x").WithLocation(14, 33) ); } [Fact] public void CS1908ERR_DefaultValueTypeMustMatch() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Bad([Optional] [DefaultParameterValue(""true"")] bool b); // CS1908 } "; CreateCompilation(text).VerifyDiagnostics( // (4,26): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } // Dev10 reports CS1909: The DefaultValue attribute is not applicable on parameters of type '{0}'. // for parameters of type System.Type or array even though there is no reason why null couldn't be specified in DPV. // We report CS1910 if DPV has an argument of type System.Type or array like Dev10 does except for we do so instead // of CS1909 when non-null is passed. [Fact] public void CS1909ERR_DefaultValueBadValueType_Array_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]int[] arr1); } "; // Dev10 reports CS1909, we don't CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Array() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(new int[] { 1, 2 })]object a); void Test2([DefaultParameterValue(new int[] { 1, 2 })]int[] a); void Test3([DefaultParameterValue(new int[0])]int[] a); } "; // CS1910 CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (5,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]"), // (6,17): error CS1910: Argument of type 'int[]' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("int[]")); } [Fact] public void CS1909ERR_DefaultValueBadValueType_Type_NoError() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(null)]System.Type t); } "; // Dev10 reports CS1909, we don't CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS1910ERR_DefaultValueBadValue_Generics() { var text = @"using System.Runtime.InteropServices; public class C { } public interface ISomeInterface { void Test1<T>([DefaultParameterValue(null)]T t); // error void Test2<T>([DefaultParameterValue(null)]T t) where T : C; // OK void Test3<T>([DefaultParameterValue(null)]T t) where T : class; // OK void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error } "; CreateCompilation(text).VerifyDiagnostics( // (6,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test1<T>([DefaultParameterValue(null)]T t); // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue"), // (9,20): error CS1908: The type of the argument to the DefaultValue attribute must match the parameter type // void Test4<T>([DefaultParameterValue(null)]T t) where T : struct; // error Diagnostic(ErrorCode.ERR_DefaultValueTypeMustMatch, "DefaultParameterValue")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type1() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]object t); // CS1910 } "; CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1910ERR_DefaultValueBadValueType_Type2() { var text = @"using System.Runtime.InteropServices; public interface ISomeInterface { void Test1([DefaultParameterValue(typeof(int))]System.Type t); // CS1910 } "; CreateCompilation(text).VerifyDiagnostics( // (4,17): error CS1910: Argument of type 'System.Type' is not applicable for the DefaultValue attribute Diagnostic(ErrorCode.ERR_DefaultValueBadValueType, "DefaultParameterValue").WithArguments("System.Type")); } [Fact] public void CS1961ERR_UnexpectedVariance() { var text = @"interface Goo<out T> { T Bar(); void Baz(T t); }"; CreateCompilation(text).VerifyDiagnostics( // (4,14): error CS1961: Invalid variance: The type parameter 'T' must be contravariantly valid on 'Goo<T>.Baz(T)'. 'T' is covariant. // void Baz(T t); Diagnostic(ErrorCode.ERR_UnexpectedVariance, "T").WithArguments("Goo<T>.Baz(T)", "T", "covariant", "contravariantly").WithLocation(4, 14)); } [Fact] public void CS1965ERR_DeriveFromDynamic() { var text = @"public class ErrorCode : dynamic { }"; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (1,26): error CS1965: 'ErrorCode': cannot derive from the dynamic type Diagnostic(ErrorCode.ERR_DeriveFromDynamic, "dynamic").WithArguments("ErrorCode")); } [Fact, WorkItem(552740, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552740")] public void CS1966ERR_DeriveFromConstructedDynamic() { var text = @" interface I<T> { } class C<T> { public enum D { } } class E1 : I<dynamic> {} class E2 : I<C<dynamic>.D*[]> {} "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics( // (11,12): error CS1966: 'E2': cannot implement a dynamic interface 'I<C<dynamic>.D*[]>' // class E2 : I<C<dynamic>.D*[]> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<C<dynamic>.D*[]>").WithArguments("E2", "I<C<dynamic>.D*[]>"), // (10,12): error CS1966: 'E1': cannot implement a dynamic interface 'I<dynamic>' // class E1 : I<dynamic> {} Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<dynamic>").WithArguments("E1", "I<dynamic>")); } [Fact] public void CS1967ERR_DynamicTypeAsBound() { var source = @"delegate void D<T>() where T : dynamic;"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (1,32): error CS1967: Constraint cannot be the dynamic type Diagnostic(ErrorCode.ERR_DynamicTypeAsBound, "dynamic")); } [Fact] public void CS1968ERR_ConstructedDynamicTypeAsBound() { var source = @"interface I<T> { } struct S<T> { internal delegate void D<U>(); } class A<T> { } class B<T, U> where T : A<S<T>.D<dynamic>>, I<dynamic[]> where U : I<S<dynamic>.D<T>> { }"; CreateCompilation(source).VerifyDiagnostics( // (8,15): error CS1968: Constraint cannot be a dynamic type 'A<S<T>.D<dynamic>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "A<S<T>.D<dynamic>>").WithArguments("A<S<T>.D<dynamic>>").WithLocation(8, 15), // (8,35): error CS1968: Constraint cannot be a dynamic type 'I<dynamic[]>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<dynamic[]>").WithArguments("I<dynamic[]>").WithLocation(8, 35), // (9,15): error CS1968: Constraint cannot be a dynamic type 'I<S<dynamic>.D<T>>' Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<S<dynamic>.D<T>>").WithArguments("I<S<dynamic>.D<T>>").WithLocation(9, 15)); } // Instead of CS1982 ERR_DynamicNotAllowedInAttribute we report CS0181 ERR_BadAttributeParamType [Fact] public void CS1982ERR_DynamicNotAllowedInAttribute_NoError() { var text = @" using System; public class C<T> { public enum D { A } } [A(T = typeof(dynamic[]))] // Dev11 reports error, but this should be ok [A(T = typeof(C<dynamic>))] [A(T = typeof(C<dynamic>[]))] [A(T = typeof(C<dynamic>.D[]))] [A(T = typeof(C<dynamic>.D*[]))] [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)] class A : Attribute { public Type T; } "; CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(); } [Fact] public void CS7021ERR_NamespaceNotAllowedInScript() { var text = @" namespace N1 { class A { public int Goo() { return 2; }} } "; var expectedDiagnostics = new[] { // (2,1): error CS7021: You cannot declare namespace in script code // namespace N1 Diagnostic(ErrorCode.ERR_NamespaceNotAllowedInScript, "namespace").WithLocation(2, 1) }; CreateCompilationWithMscorlib45(new[] { Parse(text, options: TestOptions.Script) }).VerifyDiagnostics(expectedDiagnostics); } [Fact] public void CS8050ERR_InitializerOnNonAutoProperty() { var source = @"public class C { int A { get; set; } = 1; int I { get { throw null; } set { } } = 1; static int S { get { throw null; } set { } } = 1; protected int P { get { throw null; } set { } } = 1; }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS8050: Only auto-implemented properties can have initializers. // int I { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "I").WithArguments("C.I").WithLocation(5, 9), // (6,16): error CS8050: Only auto-implemented properties can have initializers. // static int S { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "S").WithArguments("C.S").WithLocation(6, 16), // (7,19): error CS8050: Only auto-implemented properties can have initializers. // protected int P { get { throw null; } set { } } = 1; Diagnostic(ErrorCode.ERR_InitializerOnNonAutoProperty, "P").WithArguments("C.P").WithLocation(7, 19) ); } [Fact] public void ErrorTypeCandidateSymbols1() { var text = @" class A { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.TypeWithAnnotations; Assert.Equal(SymbolKind.ErrorType, fieldType.Type.Kind); Assert.Equal("B", fieldType.Type.Name); var errorFieldType = (ErrorTypeSymbol)fieldType.Type; Assert.Equal(CandidateReason.None, errorFieldType.CandidateReason); Assert.Equal(0, errorFieldType.CandidateSymbols.Length); } [Fact] public void ErrorTypeCandidateSymbols2() { var text = @" class C { private class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var classC = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("C").Single(); var classB = (NamedTypeSymbol)classC.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Inaccessible, errorFieldType.CandidateReason); Assert.Equal(1, errorFieldType.CandidateSymbols.Length); Assert.Equal(classB, errorFieldType.CandidateSymbols[0]); } [Fact] public void ErrorTypeCandidateSymbols3() { var text = @" using N1; using N2; namespace N1 { class B {} } namespace N2 { class B {} } class A : C { public B n; }"; CSharpCompilation comp = CreateCompilation(text); var classA = (NamedTypeSymbol)comp.GlobalNamespace.GetTypeMembers("A").Single(); var ns1 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N1").Single(); var ns2 = (NamespaceSymbol)comp.GlobalNamespace.GetMembers("N2").Single(); var classBinN1 = (NamedTypeSymbol)ns1.GetTypeMembers("B").Single(); var classBinN2 = (NamedTypeSymbol)ns2.GetTypeMembers("B").Single(); var fieldSym = (FieldSymbol)classA.GetMembers("n").Single(); var fieldType = fieldSym.Type; Assert.Equal(SymbolKind.ErrorType, fieldType.Kind); Assert.Equal("B", fieldType.Name); var errorFieldType = (ErrorTypeSymbol)fieldType; Assert.Equal(CandidateReason.Ambiguous, errorFieldType.CandidateReason); Assert.Equal(2, errorFieldType.CandidateSymbols.Length); Assert.True((TypeSymbol.Equals(classBinN1, (TypeSymbol)errorFieldType.CandidateSymbols[0], TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(classBinN2, (TypeSymbol)errorFieldType.CandidateSymbols[1], TypeCompareKind.ConsiderEverything2)) || (TypeSymbol.Equals(classBinN2, (TypeSymbol)errorFieldType.CandidateSymbols[0], TypeCompareKind.ConsiderEverything2) && TypeSymbol.Equals(classBinN1, (TypeSymbol)errorFieldType.CandidateSymbols[1], TypeCompareKind.ConsiderEverything2)), "CandidateSymbols must by N1.B and N2.B in some order"); } #endregion #region "Symbol Warning Tests" /// <summary> /// current error 104 /// </summary> [Fact] public void CS0105WRN_DuplicateUsing01() { var text = @"using System; using System; namespace Goo.Bar { class A { } } namespace testns { using Goo.Bar; using System; using Goo.Bar; class B : A { } }"; CreateCompilation(text).VerifyDiagnostics( // (2,7): warning CS0105: The using directive for 'System' appeared previously in this namespace // using System; Diagnostic(ErrorCode.WRN_DuplicateUsing, "System").WithArguments("System"), // (13,11): warning CS0105: The using directive for 'Goo.Bar' appeared previously in this namespace // using Goo.Bar; Diagnostic(ErrorCode.WRN_DuplicateUsing, "Goo.Bar").WithArguments("Goo.Bar"), // (1,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (12,5): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"), // (13,5): info CS8019: Unnecessary using directive. // using Goo.Bar; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using Goo.Bar;")); // TODO... // var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; } [Fact] public void CS0108WRN_NewRequired01() { var text = @"using System; namespace x { public class clx { public int i = 1; } public class cly : clx { public static int i = 2; // CS0108, use the new keyword public static void Main() { Console.WriteLine(i); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 12, Column = 27, IsWarning = true }); } [Fact] public void CS0108WRN_NewRequired02() { var source = @"class A { public static void P() { } public static void Q() { } public void R() { } public void S() { } public static int T { get; set; } public static int U { get; set; } public int V { get; set; } public int W { get; set; } } class B : A { public static int P { get; set; } // CS0108 public int Q { get; set; } // CS0108 public static int R { get; set; } // CS0108 public int S { get; set; } // CS0108 public static void T() { } // CS0108 public void U() { } // CS0108 public static void V() { } // CS0108 public void W() { } // CS0108 } "; CreateCompilation(source).VerifyDiagnostics( // (15,16): warning CS0108: 'B.Q' hides inherited member 'A.Q()'. Use the new keyword if hiding was intended. // public int Q { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "Q").WithArguments("B.Q", "A.Q()").WithLocation(15, 16), // (16,23): warning CS0108: 'B.R' hides inherited member 'A.R()'. Use the new keyword if hiding was intended. // public static int R { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "R").WithArguments("B.R", "A.R()").WithLocation(16, 23), // (17,16): warning CS0108: 'B.S' hides inherited member 'A.S()'. Use the new keyword if hiding was intended. // public int S { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "S").WithArguments("B.S", "A.S()").WithLocation(17, 16), // (18,24): warning CS0108: 'B.T()' hides inherited member 'A.T'. Use the new keyword if hiding was intended. // public static void T() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("B.T()", "A.T").WithLocation(18, 24), // (19,17): warning CS0108: 'B.U()' hides inherited member 'A.U'. Use the new keyword if hiding was intended. // public void U() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "U").WithArguments("B.U()", "A.U").WithLocation(19, 17), // (20,24): warning CS0108: 'B.V()' hides inherited member 'A.V'. Use the new keyword if hiding was intended. // public static void V() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "V").WithArguments("B.V()", "A.V").WithLocation(20, 24), // (21,17): warning CS0108: 'B.W()' hides inherited member 'A.W'. Use the new keyword if hiding was intended. // public void W() { } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "W").WithArguments("B.W()", "A.W").WithLocation(21, 17), // (14,23): warning CS0108: 'B.P' hides inherited member 'A.P()'. Use the new keyword if hiding was intended. // public static int P { get; set; } // CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "P").WithArguments("B.P", "A.P()").WithLocation(14, 23)); } [WorkItem(539624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539624")] [Fact] public void CS0108WRN_NewRequired03() { var text = @" class BaseClass { public int MyMeth(int intI) { return intI; } } class MyClass : BaseClass { public static int MyMeth(int intI) // CS0108 { return intI + 1; } } class SBase { protected static void M() {} } class DClass : SBase { protected void M() {} // CS0108 } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 13, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_NewRequired, Line = 26, Column = 20, IsWarning = true }); } [WorkItem(540459, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540459")] [Fact] public void CS0108WRN_NewRequired04() { var text = @" class A { public void f() { } } class B: A { } class C : B { public int f = 3; //CS0108 } "; CreateCompilation(text).VerifyDiagnostics( // (15,16): warning CS0108: 'C.f' hides inherited member 'A.f()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "f").WithArguments("C.f", "A.f()")); } [Fact] public void CS0108WRN_NewRequired05() { var text = @" class A { public static void SM1() { } public static void SM2() { } public static void SM3() { } public static void SM4() { } public void IM1() { } public void IM2() { } public void IM3() { } public void IM4() { } public static int SP1 { get; set; } public static int SP2 { get; set; } public static int SP3 { get; set; } public static int SP4 { get; set; } public int IP1 { get; set; } public int IP2 { get; set; } public int IP3 { get; set; } public int IP4 { get; set; } public static event System.Action SE1; public static event System.Action SE2; public static event System.Action SE3; public static event System.Action SE4; public event System.Action IE1{ add { } remove { } } public event System.Action IE2{ add { } remove { } } public event System.Action IE3{ add { } remove { } } public event System.Action IE4{ add { } remove { } } } class B : A { public static int SM1 { get; set; } //CS0108 public int SM2 { get; set; } //CS0108 public static event System.Action SM3; //CS0108 public event System.Action SM4{ add { } remove { } } //CS0108 public static int IM1 { get; set; } //CS0108 public int IM2 { get; set; } //CS0108 public static event System.Action IM3; //CS0108 public event System.Action IM4{ add { } remove { } } //CS0108 public static void SP1() { } //CS0108 public void SP2() { } //CS0108 public static event System.Action SP3; //CS0108 public event System.Action SP4{ add { } remove { } } //CS0108 public static void IP1() { } //CS0108 public void IP2() { } //CS0108 public static event System.Action IP3; //CS0108 public event System.Action IP4{ add { } remove { } } //CS0108 public static void SE1() { } //CS0108 public void SE2() { } //CS0108 public static int SE3 { get; set; } //CS0108 public int SE4 { get; set; } //CS0108 public static void IE1() { } //CS0108 public void IE2() { } //CS0108 public static int IE3 { get; set; } //CS0108 public int IE4 { get; set; } //CS0108 }"; CreateCompilation(text).VerifyDiagnostics( // (36,23): warning CS0108: 'B.SM1' hides inherited member 'A.SM1()'. Use the new keyword if hiding was intended. // public static int SM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM1").WithArguments("B.SM1", "A.SM1()"), // (37,16): warning CS0108: 'B.SM2' hides inherited member 'A.SM2()'. Use the new keyword if hiding was intended. // public int SM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM2").WithArguments("B.SM2", "A.SM2()"), // (38,39): warning CS0108: 'B.SM3' hides inherited member 'A.SM3()'. Use the new keyword if hiding was intended. // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM3").WithArguments("B.SM3", "A.SM3()"), // (39,32): warning CS0108: 'B.SM4' hides inherited member 'A.SM4()'. Use the new keyword if hiding was intended. // public event System.Action SM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SM4").WithArguments("B.SM4", "A.SM4()"), // (41,23): warning CS0108: 'B.IM1' hides inherited member 'A.IM1()'. Use the new keyword if hiding was intended. // public static int IM1 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM1").WithArguments("B.IM1", "A.IM1()"), // (42,16): warning CS0108: 'B.IM2' hides inherited member 'A.IM2()'. Use the new keyword if hiding was intended. // public int IM2 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM2").WithArguments("B.IM2", "A.IM2()"), // (43,39): warning CS0108: 'B.IM3' hides inherited member 'A.IM3()'. Use the new keyword if hiding was intended. // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM3").WithArguments("B.IM3", "A.IM3()"), // (44,32): warning CS0108: 'B.IM4' hides inherited member 'A.IM4()'. Use the new keyword if hiding was intended. // public event System.Action IM4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IM4").WithArguments("B.IM4", "A.IM4()"), // (46,24): warning CS0108: 'B.SP1()' hides inherited member 'A.SP1'. Use the new keyword if hiding was intended. // public static void SP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP1").WithArguments("B.SP1()", "A.SP1"), // (47,17): warning CS0108: 'B.SP2()' hides inherited member 'A.SP2'. Use the new keyword if hiding was intended. // public void SP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP2").WithArguments("B.SP2()", "A.SP2"), // (48,39): warning CS0108: 'B.SP3' hides inherited member 'A.SP3'. Use the new keyword if hiding was intended. // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP3").WithArguments("B.SP3", "A.SP3"), // (49,32): warning CS0108: 'B.SP4' hides inherited member 'A.SP4'. Use the new keyword if hiding was intended. // public event System.Action SP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SP4").WithArguments("B.SP4", "A.SP4"), // (51,24): warning CS0108: 'B.IP1()' hides inherited member 'A.IP1'. Use the new keyword if hiding was intended. // public static void IP1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP1").WithArguments("B.IP1()", "A.IP1"), // (52,17): warning CS0108: 'B.IP2()' hides inherited member 'A.IP2'. Use the new keyword if hiding was intended. // public void IP2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP2").WithArguments("B.IP2()", "A.IP2"), // (53,39): warning CS0108: 'B.IP3' hides inherited member 'A.IP3'. Use the new keyword if hiding was intended. // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP3").WithArguments("B.IP3", "A.IP3"), // (54,32): warning CS0108: 'B.IP4' hides inherited member 'A.IP4'. Use the new keyword if hiding was intended. // public event System.Action IP4{ add { } remove { } } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IP4").WithArguments("B.IP4", "A.IP4"), // (56,24): warning CS0108: 'B.SE1()' hides inherited member 'A.SE1'. Use the new keyword if hiding was intended. // public static void SE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE1").WithArguments("B.SE1()", "A.SE1"), // (57,17): warning CS0108: 'B.SE2()' hides inherited member 'A.SE2'. Use the new keyword if hiding was intended. // public void SE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE2").WithArguments("B.SE2()", "A.SE2"), // (58,23): warning CS0108: 'B.SE3' hides inherited member 'A.SE3'. Use the new keyword if hiding was intended. // public static int SE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE3").WithArguments("B.SE3", "A.SE3"), // (59,16): warning CS0108: 'B.SE4' hides inherited member 'A.SE4'. Use the new keyword if hiding was intended. // public int SE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "SE4").WithArguments("B.SE4", "A.SE4"), // (61,24): warning CS0108: 'B.IE1()' hides inherited member 'A.IE1'. Use the new keyword if hiding was intended. // public static void IE1() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE1").WithArguments("B.IE1()", "A.IE1"), // (62,17): warning CS0108: 'B.IE2()' hides inherited member 'A.IE2'. Use the new keyword if hiding was intended. // public void IE2() { } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE2").WithArguments("B.IE2()", "A.IE2"), // (63,23): warning CS0108: 'B.IE3' hides inherited member 'A.IE3'. Use the new keyword if hiding was intended. // public static int IE3 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE3").WithArguments("B.IE3", "A.IE3"), // (64,16): warning CS0108: 'B.IE4' hides inherited member 'A.IE4'. Use the new keyword if hiding was intended. // public int IE4 { get; set; } //CS0108 Diagnostic(ErrorCode.WRN_NewRequired, "IE4").WithArguments("B.IE4", "A.IE4"), // (53,39): warning CS0067: The event 'B.IP3' is never used // public static event System.Action IP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IP3").WithArguments("B.IP3"), // (25,39): warning CS0067: The event 'A.SE2' is never used // public static event System.Action SE2; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE2").WithArguments("A.SE2"), // (26,39): warning CS0067: The event 'A.SE3' is never used // public static event System.Action SE3; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE3").WithArguments("A.SE3"), // (38,39): warning CS0067: The event 'B.SM3' is never used // public static event System.Action SM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SM3").WithArguments("B.SM3"), // (279): warning CS0067: The event 'A.SE4' is never used // public static event System.Action SE4; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE4").WithArguments("A.SE4"), // (48,39): warning CS0067: The event 'B.SP3' is never used // public static event System.Action SP3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SP3").WithArguments("B.SP3"), // (24,39): warning CS0067: The event 'A.SE1' is never used // public static event System.Action SE1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "SE1").WithArguments("A.SE1"), // (43,39): warning CS0067: The event 'B.IM3' is never used // public static event System.Action IM3; //CS0108 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "IM3").WithArguments("B.IM3")); } [WorkItem(539624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539624")] [Fact] public void CS0108WRN_NewRequired_Arity() { var text = @" class Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } class HideWithClass : Class { public class T { } public class T<A> { } public class T<A, B> { } public class T<A, B, C> { } public class M { } public class M<A> { } public class M<A, B> { } public class M<A, B, C> { } public class D { } public class D<A> { } public class D<A, B> { } public class D<A, B, C> { } } class HideWithMethod : Class { public void T() { } public void T<A>() { } public void T<A, B>() { } public void T<A, B, C>() { } public void M() { } public void M<A>() { } public void M<A, B>() { } public void M<A, B, C>() { } public void D() { } public void D<A>() { } public void D<A, B>() { } public void D<A, B, C>() { } } class HideWithDelegate : Class { public delegate void T(); public delegate void T<A>(); public delegate void T<A, B>(); public delegate void T<A, B, C>(); public delegate void M(); public delegate void M<A>(); public delegate void M<A, B>(); public delegate void M<A, B, C>(); public delegate void D(); public delegate void D<A>(); public delegate void D<A, B>(); public delegate void D<A, B, C>(); } "; CreateCompilation(text).VerifyDiagnostics( /* HideWithClass */ // (22,18): warning CS0108: 'HideWithClass.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T", "Class.T"), // (23,18): warning CS0108: 'HideWithClass.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A>", "Class.T<A>"), // (24,18): warning CS0108: 'HideWithClass.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B>", "Class.T<A, B>"), // (25,18): warning CS0108: 'HideWithClass.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithClass.T<A, B, C>", "Class.T<A, B, C>"), // (27,18): warning CS0108: 'HideWithClass.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M", "Class.M()"), // (28,18): warning CS0108: 'HideWithClass.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A>", "Class.M<A>()"), // (29,18): warning CS0108: 'HideWithClass.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B>", "Class.M<A, B>()"), // (30,18): warning CS0108: 'HideWithClass.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithClass.M<A, B, C>", "Class.M<A, B, C>()"), // (32,18): warning CS0108: 'HideWithClass.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D", "Class.D"), // (33,18): warning CS0108: 'HideWithClass.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A>", "Class.D<A>"), // (34,18): warning CS0108: 'HideWithClass.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B>", "Class.D<A, B>"), // (35,18): warning CS0108: 'HideWithClass.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithClass.D<A, B, C>", "Class.D<A, B, C>"), /* HideWithMethod */ // (40,17): warning CS0108: 'HideWithMethod.T()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T()", "Class.T"), // (41,17): warning CS0108: 'HideWithMethod.T<A>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A>()", "Class.T"), // (42,17): warning CS0108: 'HideWithMethod.T<A, B>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B>()", "Class.T"), // (43,17): warning CS0108: 'HideWithMethod.T<A, B, C>()' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithMethod.T<A, B, C>()", "Class.T"), // (45,17): warning CS0108: 'HideWithMethod.M()' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M()", "Class.M()"), // (46,17): warning CS0108: 'HideWithMethod.M<A>()' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A>()", "Class.M<A>()"), // (47,17): warning CS0108: 'HideWithMethod.M<A, B>()' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B>()", "Class.M<A, B>()"), // (48,17): warning CS0108: 'HideWithMethod.M<A, B, C>()' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithMethod.M<A, B, C>()", "Class.M<A, B, C>()"), // (50,17): warning CS0108: 'HideWithMethod.D()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D()", "Class.D"), // (51,17): warning CS0108: 'HideWithMethod.D<A>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A>()", "Class.D"), // (52,17): warning CS0108: 'HideWithMethod.D<A, B>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B>()", "Class.D"), // (53,17): warning CS0108: 'HideWithMethod.D<A, B, C>()' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithMethod.D<A, B, C>()", "Class.D"), /* HideWithDelegate */ // (58,26): warning CS0108: 'HideWithDelegate.T' hides inherited member 'Class.T'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T", "Class.T"), // (59,26): warning CS0108: 'HideWithDelegate.T<A>' hides inherited member 'Class.T<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A>", "Class.T<A>"), // (60,26): warning CS0108: 'HideWithDelegate.T<A, B>' hides inherited member 'Class.T<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B>", "Class.T<A, B>"), // (61,26): warning CS0108: 'HideWithDelegate.T<A, B, C>' hides inherited member 'Class.T<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "T").WithArguments("HideWithDelegate.T<A, B, C>", "Class.T<A, B, C>"), // (63,26): warning CS0108: 'HideWithDelegate.M' hides inherited member 'Class.M()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M", "Class.M()"), // (64,26): warning CS0108: 'HideWithDelegate.M<A>' hides inherited member 'Class.M<A>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A>", "Class.M<A>()"), // (65,26): warning CS0108: 'HideWithDelegate.M<A, B>' hides inherited member 'Class.M<A, B>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B>", "Class.M<A, B>()"), // (66,26): warning CS0108: 'HideWithDelegate.M<A, B, C>' hides inherited member 'Class.M<A, B, C>()'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("HideWithDelegate.M<A, B, C>", "Class.M<A, B, C>()"), // (68,26): warning CS0108: 'HideWithDelegate.D' hides inherited member 'Class.D'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D", "Class.D"), // (69,26): warning CS0108: 'HideWithDelegate.D<A>' hides inherited member 'Class.D<A>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A>", "Class.D<A>"), // (70,26): warning CS0108: 'HideWithDelegate.D<A, B>' hides inherited member 'Class.D<A, B>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B>", "Class.D<A, B>"), // (71,26): warning CS0108: 'HideWithDelegate.D<A, B, C>' hides inherited member 'Class.D<A, B, C>'. Use the new keyword if hiding was intended. Diagnostic(ErrorCode.WRN_NewRequired, "D").WithArguments("HideWithDelegate.D<A, B, C>", "Class.D<A, B, C>")); } [Fact, WorkItem(546736, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546736")] public void CS0108WRN_NewRequired_Partial() { var text = @" partial class Parent { partial void PM(int x); private void M(int x) { } partial class Child : Parent { partial void PM(int x); private void M(int x) { } } } partial class AnotherChild : Parent { partial void PM(int x); private void M(int x) { } } "; CreateCompilation(text).VerifyDiagnostics( Diagnostic(ErrorCode.WRN_NewRequired, "PM").WithArguments("Parent.Child.PM(int)", "Parent.PM(int)"), Diagnostic(ErrorCode.WRN_NewRequired, "M").WithArguments("Parent.Child.M(int)", "Parent.M(int)")); } [Fact] public void CS0109WRN_NewNotRequired() { var text = @"namespace x { public class a { public int i; } public class b : a { public new int i; public new int j; // CS0109 public static void Main() { } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NewNotRequired, Line = 11, Column = 24, IsWarning = true }); } [Fact] public void CS0114WRN_NewOrOverrideExpected() { var text = @"abstract public class clx { public abstract void f(); } public class cly : clx { public void f() // CS0114, hides base class member { } public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription[] { new ErrorDescription { Code = (int)ErrorCode.WRN_NewOrOverrideExpected, Line = 8, Column = 17, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.ERR_UnimplementedAbstractMethod, Line = 6, Column = 14 } }); } [Fact] public void CS0282WRN_SequentialOnPartialClass() { var text = @" partial struct A { int i; } partial struct A { int j; } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (1,16): warning CS0282: There is no defined ordering between fields in multiple declarations of partial struct 'A'. To specify an ordering, all instance fields must be in the same declaration. // partial struct A Diagnostic(ErrorCode.WRN_SequentialOnPartialClass, "A").WithArguments("A"), // (3,9): warning CS0169: The field 'A.i' is never used // int i; Diagnostic(ErrorCode.WRN_UnreferencedField, "i").WithArguments("A.i"), // (7,9): warning CS0169: The field 'A.j' is never used // int j; Diagnostic(ErrorCode.WRN_UnreferencedField, "j").WithArguments("A.j")); } [Fact] [WorkItem(23668, "https://github.com/dotnet/roslyn/issues/23668")] public void CS0282WRN_PartialWithPropertyButSingleField() { string program = @"partial struct X // No warning CS0282 { // The only field of X is a backing field of A. public int A { get; set; } } partial struct X : I { // This partial definition has no field. int I.A { get => A; set => A = value; } } interface I { int A { get; set; } }"; var comp = CreateCompilation(program); comp.VerifyDiagnostics(); } /// <summary> /// import - Lib: class A { class B {} } /// vs. curr: Namespace A { class B {} } - use B /// </summary> [ClrOnlyFact(ClrOnlyReason.Unknown)] public void CS0435WRN_SameFullNameThisNsAgg01() { var text = @"namespace CSFields { public class FFF { } } namespace SA { class Test { CSFields.FFF var = null; void M(CSFields.FFF p) { } } } "; // class CSFields { class FFF {}} var ref1 = TestReferences.SymbolsTests.Fields.CSFields.dll; var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // void M(CSFields.FFF p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,9): warning CS0435: The namespace 'CSFields' in '' conflicts with the imported type 'CSFields' in 'CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in ''. // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CSFields").WithArguments("", "CSFields", "CSFields, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CSFields"), // (10,22): warning CS0414: The field 'SA.Test.var' is assigned but its value is never used // CSFields.FFF var = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "var").WithArguments("SA.Test.var") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } /// <summary> /// import - Lib: class A {} vs. curr: class A { } /// </summary> [Fact] public void CS0436WRN_SameFullNameThisAggAgg01() { var text = @"class Class1 { } namespace SA { class Test { Class1 cls; void M(Class1 p) { } } } "; // Class1 var ref1 = TestReferences.SymbolsTests.V1.MTTestLib1.dll; // Roslyn gives CS1542 or CS0104 var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (8,16): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(Class1 p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,9): warning CS0436: The type 'Class1' in '' conflicts with the imported type 'Class1' in 'MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // Class1 cls; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Class1").WithArguments("", "Class1", "MTTestLib1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Class1"), // (7,16): warning CS0169: The field 'SA.Test.cls' is never used // Class1 cls; Diagnostic(ErrorCode.WRN_UnreferencedField, "cls").WithArguments("SA.Test.cls")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [Fact] [WorkItem(546077, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546077")] public void MultipleSymbolDisambiguation() { var sourceRef1 = @" public class CCC { public class X { } } public class CNC { public class X { } } namespace NCC { public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } public class CNN { public class X { } } namespace NCN { public class X { } } namespace NNN { public class X { } } "; var sourceRef2 = @" public class CCC { public class X { } } namespace CNC { public class X { } } public class NCC{ public class X { } } namespace NNC { public class X { } } public class CCN { public class X { } } namespace CNN { public class X { } } public class NCN { public class X { } } namespace NNN { public class X { } } "; var sourceLib = @" public class CCC { public class X { } } namespace CCN { public class X { } } public class CNC { public class X { } } namespace CNN { public class X { } } public class NCC { public class X { } } namespace NCN { public class X { } } public class NNC { public class X { } } namespace NNN { public class X { } } internal class DC : CCC.X { } internal class DN : CCN.X { } internal class D3 : CNC.X { } internal class D4 : CNN.X { } internal class D5 : NCC.X { } internal class D6 : NCN.X { } internal class D7 : NNC.X { } internal class D8 : NNN.X { } "; var ref1 = CreateCompilation(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilation(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilation(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // In some cases we might order the symbols differently than Dev11 and thus reporting slightly different warnings. // E.g. (src:type, md:type, md:namespace) vs (src:type, md:namespace, md:type) // We report (type, type) ambiguity while Dev11 reports (type, namespace) ambiguity, but both are equally correct. // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. lib.VerifyDiagnostics( // C:\lib.cs(12,21): warning CS0435: The namespace 'CCN' in 'C:\lib.cs' conflicts with the imported type 'CCN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CCN").WithArguments(@"C:\lib.cs", "CCN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCN"), // C:\lib.cs(16,21): warning CS0435: The namespace 'NCN' in 'C:\lib.cs' conflicts with the imported type 'NCN' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "NCN").WithArguments(@"C:\lib.cs", "NCN", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN"), // C:\lib.cs(16,25): warning CS0436: The type 'NCN.X' in 'C:\lib.cs' conflicts with the imported type 'NCN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NCN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCN.X"), // C:\lib.cs(11,21): warning CS0436: The type 'CCC' in 'C:\lib.cs' conflicts with the imported type 'CCC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CCC").WithArguments(@"C:\lib.cs", "CCC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CCC"), // C:\lib.cs(15,21): warning CS0436: The type 'NCC' in 'C:\lib.cs' conflicts with the imported type 'NCC' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "NCC").WithArguments(@"C:\lib.cs", "NCC", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NCC"), // C:\lib.cs(13,21): warning CS0436: The type 'CNC' in 'C:\lib.cs' conflicts with the imported type 'CNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "CNC").WithArguments(@"C:\lib.cs", "CNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNC"), // C:\lib.cs(14,21): warning CS0435: The namespace 'CNN' in 'C:\lib.cs' conflicts with the imported type 'CNN' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the namespace defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisNsAgg, "CNN").WithArguments(@"C:\lib.cs", "CNN", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN"), // C:\lib.cs(14,25): warning CS0436: The type 'CNN.X' in 'C:\lib.cs' conflicts with the imported type 'CNN.X' in 'Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "CNN.X", "Ref2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "CNN.X"), // C:\lib.cs(17,21): warning CS0437: The type 'NNC' in 'C:\lib.cs' conflicts with the imported namespace 'NNC' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "NNC").WithArguments(@"C:\lib.cs", "NNC", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNC"), // C:\lib.cs(18,25): warning CS0436: The type 'NNN.X' in 'C:\lib.cs' conflicts with the imported type 'NNN.X' in 'Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in 'C:\lib.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "X").WithArguments(@"C:\lib.cs", "NNN.X", "Ref1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "NNN.X")); } [Fact] public void MultipleSourceSymbols1() { var sourceLib = @" public class C { } namespace C { } public class D : C { }"; // do not report lookup errors CreateCompilation(sourceLib).VerifyDiagnostics( // error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [Fact] public void MultipleSourceSymbols2() { var sourceRef1 = @" public class C { public class X { } } "; var sourceRef2 = @" namespace N { public class X { } } "; var sourceLib = @" public class C { public class X { } } namespace C { public class X { } } internal class D : C.X { } "; var ref1 = CreateCompilation(sourceRef1, assemblyName: "Ref1").VerifyDiagnostics(); var ref2 = CreateCompilation(sourceRef2, assemblyName: "Ref2").VerifyDiagnostics(); var tree = Parse(sourceLib, filename: @"C:\lib.cs"); var lib = CreateCompilation(tree, new MetadataReference[] { new CSharpCompilationReference(ref1), new CSharpCompilationReference(ref2), }); // do not report lookup errors lib.VerifyDiagnostics( // C:\lib.cs(2,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>")); } [WorkItem(545725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545725")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg02() { var text = @" namespace System { class Int32 { const Int32 MaxValue = null; static void Main() { Int32 x = System.Int32.MaxValue; } } } "; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }).VerifyDiagnostics( // goo.cs(6,15): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,13): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,23): warning CS0436: The type 'System.Int32' in 'goo.cs' conflicts with the imported type 'int' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "System.Int32").WithArguments("goo.cs", "System.Int32", RuntimeCorLibName.FullName, "int"), // goo.cs(9,19): warning CS0219: The variable 'x' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x")); } [WorkItem(538320, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538320")] [Fact] public void CS0436WRN_SameFullNameThisAggAgg03() { var text = @"namespace System { class Object { static void Main() { Console.WriteLine(""hello""); } } class Goo : object {} class Bar : Object {} }"; // TODO (tomat): // We should report a path to an assembly rather than the assembly name when reporting an error. CreateCompilation(new SyntaxTree[] { Parse(text, "goo.cs") }).VerifyDiagnostics( // goo.cs(11,17): warning CS0436: The type 'System.Object' in 'goo.cs' conflicts with the imported type 'object' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in 'goo.cs'. Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Object").WithArguments("goo.cs", "System.Object", RuntimeCorLibName.FullName, "object")); } /// <summary> /// import- Lib: namespace A { class B{} } vs. curr: class A { class B {} } /// </summary> [Fact] public void CS0437WRN_SameFullNameThisAggNs01() { var text = @"public class AppCS { public class App { } } namespace SA { class Test { AppCS.App app = null; void M(AppCS.App p) { } } } "; // this is not related to this test, but need by lib2 (don't want to add a new dll resource) var cs00 = TestReferences.MetadataTests.NetModule01.ModuleCS00; var cs01 = TestReferences.MetadataTests.NetModule01.ModuleCS01; var vb01 = TestReferences.MetadataTests.NetModule01.ModuleVB01; var ref1 = TestReferences.MetadataTests.NetModule01.AppCS; // Roslyn CS1542 var comp = CreateCompilation(new[] { text }, new List<MetadataReference> { ref1 }); comp.VerifyDiagnostics( // (11,16): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // void M(AppCS.App p) { } Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,9): warning CS0437: The type 'AppCS' in '' conflicts with the imported namespace 'AppCS' in 'AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''. // AppCS.App app = null; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "AppCS").WithArguments("", "AppCS", "AppCS, Version=1.2.3.4, Culture=neutral, PublicKeyToken=null", "AppCS"), // (10,19): warning CS0414: The field 'SA.Test.app' is assigned but its value is never used // AppCS.App app = null; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "app").WithArguments("SA.Test.app")); var ns = comp.SourceModule.GlobalNamespace.GetMembers("SA").Single() as NamespaceSymbol; // TODO... } [WorkItem(545649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545649")] [Fact] public void CS0437WRN_SameFullNameThisAggNs02() { var source = @" using System; class System { } "; // NOTE: both mscorlib.dll and System.Core.dll define types in the System namespace. var compilation = CreateCompilation( Parse(source, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); compilation.VerifyDiagnostics( // (2,7): warning CS0437: The type 'System' in '' conflicts with the imported namespace 'System' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // using System; Diagnostic(ErrorCode.WRN_SameFullNameThisAggNs, "System").WithArguments("", "System", RuntimeCorLibName.FullName, "System"), // (2,7): error CS0138: A using namespace directive can only be applied to namespaces; 'System' is a type not a namespace // using System; Diagnostic(ErrorCode.ERR_BadUsingNamespace, "System").WithArguments("System"), // (2,1): info CS8019: Unnecessary using directive. // using System; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")); } [Fact] public void CS0465WRN_FinalizeMethod() { var text = @" class A { protected virtual void Finalize() {} // CS0465 } abstract class B { public abstract void Finalize(); // CS0465 } abstract class C { protected int Finalize() {return 0;} // No Warning protected abstract void Finalize(int x); // No Warning protected virtual void Finalize<T>() { } // No Warning } class D : C { protected override void Finalize(int x) { } // No Warning protected override void Finalize<U>() { } // No Warning }"; CreateCompilation(text).VerifyDiagnostics( // (4,27): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize"), // (9,25): warning CS0465: Introducing a 'Finalize' method can interfere with destructor invocation. Did you intend to declare a destructor? Diagnostic(ErrorCode.WRN_FinalizeMethod, "Finalize")); } [Fact] public void CS0473WRN_ExplicitImplCollision() { var text = @"public interface ITest<T> { int TestMethod(int i); int TestMethod(T i); } public class ImplementingClass : ITest<int> { int ITest<int>.TestMethod(int i) // CS0473 { return i + 1; } public int TestMethod(int i) { return i - 1; } } class T { static int Main() { return 0; } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ExplicitImplCollision, Line = 9, Column = 20, IsWarning = true }); } [Fact] public void CS0626WRN_ExternMethodNoImplementation01() { var source = @"class A : System.Attribute { } class B { extern void M(); extern object P1 { get; set; } extern static public bool operator !(B b); } class C { [A] extern void M(); [A] extern object P1 { get; set; } [A] extern static public bool operator !(C c); }"; CreateCompilation(source).VerifyDiagnostics( // (4,17): warning CS0626: Method, operator, or accessor 'B.M()' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("B.M()").WithLocation(4, 17), // (5,24): warning CS0626: Method, operator, or accessor 'B.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("B.P1.get").WithLocation(5, 24), // (5,29): warning CS0626: Method, operator, or accessor 'B.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("B.P1.set").WithLocation(5, 29), // (6,40): warning CS0626: Method, operator, or accessor 'B.operator !(B)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "!").WithArguments("B.operator !(B)").WithLocation(6, 40), // (11,28): warning CS0626: Method, operator, or accessor 'C.P1.get' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "get").WithArguments("C.P1.get").WithLocation(11, 28), // (11,33): warning CS0626: Method, operator, or accessor 'C.P1.set' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "set").WithArguments("C.P1.set").WithLocation(11, 33)); } [WorkItem(544660, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544660")] [WorkItem(530324, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530324")] [Fact] public void CS0626WRN_ExternMethodNoImplementation02() { var source = @"class A : System.Attribute { } delegate void D(); class C { extern event D E1; [A] extern event D E2; }"; CreateCompilation(source).VerifyDiagnostics( // (5,20): warning CS0626: Method, operator, or accessor 'C.E1.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern event D E1; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E1").WithArguments("C.E1.remove").WithLocation(5, 20), // (6,24): warning CS0626: Method, operator, or accessor 'C.E2.remove' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // [A] extern event D E2; Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "E2").WithArguments("C.E2.remove").WithLocation(6, 24)); } [Fact] public void CS0628WRN_ProtectedInSealed01() { var text = @"namespace NS { sealed class Goo { protected int i = 0; protected internal void M() { } } sealed public class Bar<T> { internal protected void M1(T t) { } protected V M2<V>(T t) { return default(V); } } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 5, Column = 23, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 6, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 11, Column = 33, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 12, Column = 21, IsWarning = true }); } [Fact] public void CS0628WRN_ProtectedInSealed02() { var text = @"sealed class C { protected object P { get { return null; } } public int Q { get; protected set; } } sealed class C<T> { internal protected T P { get; protected set; } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 3, Column = 22, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 4, Column = 35, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 26, IsWarning = true }, new ErrorDescription { Code = (int)ErrorCode.WRN_ProtectedInSealed, Line = 8, Column = 45, IsWarning = true }); } [WorkItem(539588, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539588")] [Fact] public void CS0628WRN_ProtectedInSealed03() { var text = @"abstract class C { protected abstract void M(); protected internal virtual int P { get { return 0; } } } sealed class D : C { protected override void M() { } protected internal override int P { get { return 0; } } protected void N() { } // CS0628 protected internal int Q { get { return 0; } } // CS0628 protected class Nested {} // CS0628 } "; CreateCompilation(text).VerifyDiagnostics( // (13,21): warning CS0628: 'D.Nested': new protected member declared in sealed type // protected class Nested {} // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Nested").WithArguments("D.Nested"), // (11,28): warning CS0628: 'D.Q': new protected member declared in sealed type // protected internal int Q { get { return 0; } } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "Q").WithArguments("D.Q"), // (10,20): warning CS0628: 'D.N()': new protected member declared in sealed type // protected void N() { } // CS0628 Diagnostic(ErrorCode.WRN_ProtectedInSealed, "N").WithArguments("D.N()") ); } [Fact] public void CS0628WRN_ProtectedInSealed04() { var text = @" sealed class C { protected event System.Action E; } "; CreateCompilation(text).VerifyDiagnostics( // (4,35): warning CS0628: 'C.E': new protected member declared in sealed type // protected event System.Action E; Diagnostic(ErrorCode.WRN_ProtectedInSealed, "E").WithArguments("C.E"), // (4,35): warning CS0067: The event 'C.E' is never used // protected event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E")); } [Fact] public void CS0628WRN_ProtectedInSealed05() { const string text = @" abstract class C { protected C() { } } sealed class D : C { protected override D() { } protected D(byte b) { } protected internal D(short s) { } internal protected D(int i) { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,24): error CS0106: The modifier 'override' is not valid for this item // protected override D() { } Diagnostic(ErrorCode.ERR_BadMemberFlag, "D").WithArguments("override").WithLocation(9, 24), // (10,15): warning CS0628: 'D.D(byte)': new protected member declared in sealed type // protected D(byte b) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(byte)").WithLocation(10, 15), // (11,24): warning CS0628: 'D.D(short)': new protected member declared in sealed type // protected internal D(short s) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(short)").WithLocation(11, 24), // (12,24): warning CS0628: 'D.D(int)': new protected member declared in sealed type // internal protected D(int i) { } Diagnostic(ErrorCode.WRN_ProtectedInSealed, "D").WithArguments("D.D(int)").WithLocation(12, 24)); } [Fact] public void CS0659WRN_EqualsWithoutGetHashCode() { var text = @"class Test { public override bool Equals(object o) { return true; } // CS0659 } // However the warning should NOT be produced if the Equals is not a 'real' override // of Equals. Neither of these should produce a warning: class Test2 { public new virtual bool Equals(object o) { return true; } } class Test3 : Test2 { public override bool Equals(object o) { return true; } } "; CreateCompilation(text).VerifyDiagnostics( // (1,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals() { var text = @" class TestBase { public new virtual bool Equals(object o) { return true; } } class Test : TestBase // CS0660 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } // This does not count! public override bool Equals(object o) { return true; } public override int GetHashCode() { return 0; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,7): warning CS0660: 'Test' defines operator == or operator != but does not override Object.Equals(object o) Diagnostic(ErrorCode.WRN_EqualityOpWithoutEquals, "Test").WithArguments("Test")); } [Fact] public void CS0660WRN_EqualityOpWithoutEquals_NoWarningWhenOverriddenWithDynamicParameter() { string source = @" public class C { public override bool Equals(dynamic o) { return false; } public static bool operator ==(C v1, C v2) { return true; } public static bool operator !=(C v1, C v2) { return false; } public override int GetHashCode() { return base.GetHashCode(); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(); } [Fact] public void CS0661WRN_EqualityOpWithoutGetHashCode() { var text = @" class TestBase { // This does not count; it has to be overridden on Test. public override int GetHashCode() { return 123; } } class Test : TestBase // CS0661 { public static bool operator ==(object o, Test t) { return true; } public static bool operator !=(object o, Test t) { return true; } public override bool Equals(object o) { return true; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,7): warning CS0659: 'Test' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "Test").WithArguments("Test"), // (7,7): warning CS0661: 'Test' defines operator == or operator != but does not override Object.GetHashCode() // class Test : TestBase // CS0661 Diagnostic(ErrorCode.WRN_EqualityOpWithoutGetHashCode, "Test").WithArguments("Test") ); } [Fact()] public void CS0672WRN_NonObsoleteOverridingObsolete() { var text = @"class MyClass { [System.Obsolete] public virtual void ObsoleteMethod() { } } class MyClass2 : MyClass { public override void ObsoleteMethod() // CS0672 { } } class MainClass { static public void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_NonObsoleteOverridingObsolete, Line = 11, Column = 26, IsWarning = true }); } [Fact()] public void CS0684WRN_CoClassWithoutComImport() { var text = @" using System.Runtime.InteropServices; [CoClass(typeof(C))] // CS0684 interface I { } class C { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CoClassWithoutComImport, Line = 4, Column = 2, IsWarning = true }); } [Fact()] public void CS0809WRN_ObsoleteOverridingNonObsolete() { var text = @"public class Base { public virtual void Test1() { } } public class C : Base { [System.Obsolete()] public override void Test1() // CS0809 { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_ObsoleteOverridingNonObsolete, Line = 10, Column = 26, IsWarning = true }); } [Fact] public void CS0824WRN_ExternCtorNoImplementation01() { var source = @"namespace NS { public class C<T> { extern C(); struct S { extern S(string s); } } }"; CreateCompilation(source).VerifyDiagnostics( // (5,16): warning CS0824: Constructor 'NS.C<T>.C()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "C").WithArguments("NS.C<T>.C()").WithLocation(5, 16), // (9,20): warning CS0824: Constructor 'NS.C<T>.S.S(string)' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "S").WithArguments("NS.C<T>.S.S(string)").WithLocation(9, 20)); } [WorkItem(540859, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540859")] [Fact] public void CS0824WRN_ExternCtorNoImplementation02() { var source = @"class A : System.Attribute { } class B { extern static B(); } class C { [A] extern static C(); }"; CreateCompilation(source).VerifyDiagnostics( // (4,19): warning CS0824: Constructor 'B.B()' is marked external Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(4, 19)); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation03() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B(); } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); var verifier = CompileAndVerify(comp, verify: Verification.Skipped). VerifyDiagnostics( // (8,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(8, 17) ); var methods = verifier.TestData.GetMethodsByName().Keys; Assert.True(methods.Any(n => n.StartsWith("A..ctor", StringComparison.Ordinal))); Assert.False(methods.Any(n => n.StartsWith("B..ctor", StringComparison.Ordinal))); // Haven't tried to emit it } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation04() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation05() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(unknown); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); // Dev12 : error CS1514: { expected // error CS1513: } expected comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(unknown); // error Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation06() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() : base(1) {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS8091: 'B.B()' cannot be extern and have a constructor initializer // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasConstructorInitializer, "B").WithArguments("B.B()").WithLocation(8, 17), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() : base(1) {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation07() { var source = @" public class A { public A(int a) { } } public class B : A { public extern B() {} }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // public extern B() {} Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation08() { var source = @" public class B { private int x = 1; public extern B(); }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyEmitDiagnostics( // (5,17): warning CS0824: Constructor 'B.B()' is marked external // public extern B(); Diagnostic(ErrorCode.WRN_ExternCtorNoImplementation, "B").WithArguments("B.B()").WithLocation(5, 17), // (4,15): warning CS0414: The field 'B.x' is assigned but its value is never used // private int x = 1; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("B.x").WithLocation(4, 15) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation09() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base(); // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base(); // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23) ); } [WorkItem(1084682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1084682"), WorkItem(1036359, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1036359"), WorkItem(386, "CodePlex")] [Fact] public void CS0824WRN_ExternCtorNoImplementation10() { var source = @" public class A { public A() { } } public class B : A { static extern B() : base() {} // error }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (8,23): error CS0514: 'B': static constructor cannot have an explicit 'this' or 'base' constructor call // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_StaticConstructorWithExplicitConstructorCall, "base").WithArguments("B").WithLocation(8, 23), // (8,17): error CS0179: 'B.B()' cannot be extern and declare a body // static extern B() : base() {} // error Diagnostic(ErrorCode.ERR_ExternHasBody, "B").WithArguments("B.B()").WithLocation(8, 17) ); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation01() { // Slight change from the native compiler; in the native compiler the "int" gets the green squiggle. // This seems wrong; the error should either highlight the parameter "x" or the initializer " = 2". // I see no reason to highlight the "int". I've changed it to highlight the "x". var compilation = CreateCompilation( @"interface IFace { int Goo(int x = 1); } class B : IFace { int IFace.Goo(int x = 2) { return 0; } }"); compilation.VerifyDiagnostics( // (7,23): error CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithLocation(7, 23).WithArguments("x")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation02() { var compilation = CreateCompilation( @"interface I { object this[string index = null] { get; } //CS1066 object this[char c, char d] { get; } //CS1066 } class C : I { object I.this[string index = ""apple""] { get { return null; } } //CS1066 internal object this[int x, int y = 0] { get { return null; } } //fine object I.this[char c = 'c', char d = 'd'] { get { return null; } } //CS1066 x2 } "); compilation.VerifyDiagnostics( // (3,24): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (7,26): warning CS1066: The default value specified for parameter 'index' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "index").WithArguments("index"), // (10,24): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (10,38): warning CS1066: The default value specified for parameter 'd' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "d").WithArguments("d")); } [Fact] public void CS1066WRN_DefaultValueForUnconsumedLocation03() { var compilation = CreateCompilation( @" class C { public static C operator!(C c = null) { return c; } public static implicit operator int(C c = null) { return 0; } } "); compilation.VerifyDiagnostics( // (4,33): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static C operator!(C c = null) { return c; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c"), // (5,43): warning CS1066: The default value specified for parameter 'c' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // public static implicit operator int(C c = null) { return 0; } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "c").WithArguments("c") ); } // public void CS1698WRN_AssumedMatchThis() => Move to CommandLineTest [Fact] public void CS1699WRN_UseSwitchInsteadOfAttribute_RoslynWRN73() { var text = @" [assembly:System.Reflection.AssemblyDelaySign(true)] // CS1699 "; // warning CS1699: Use command line option '/delaysign' or appropriate project settings instead of 'System.Reflection.AssemblyDelaySign' // Diagnostic(ErrorCode.WRN_UseSwitchInsteadOfAttribute, @"/delaysign").WithArguments(@"/delaysign", "System.Reflection.AssemblyDelaySign") // warning CS1607: Assembly generation -- Delay signing was requested, but no key was given CreateCompilation(text).VerifyDiagnostics( // warning CS73: Delay signing was specified and requires a public key, but no public key was specified Diagnostic(ErrorCode.WRN_DelaySignButNoKey) ); } [Fact(), WorkItem(544447, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544447")] public void CS1700WRN_InvalidAssemblyName() { var text = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo(""' '"")] // ok [assembly: InternalsVisibleTo(""\t\r\n;a"")] // ok (whitespace escape) [assembly: InternalsVisibleTo(""\u1234;a"")] // ok (assembly name Unicode escape) [assembly: InternalsVisibleTo(""' a '"")] // ok [assembly: InternalsVisibleTo(""\u1000000;a"")] // invalid escape [assembly: InternalsVisibleTo(""a'b'c"")] // quotes in the middle [assembly: InternalsVisibleTo(""Test, PublicKey=Null"")] [assembly: InternalsVisibleTo(""Test, Bar"")] [assembly: InternalsVisibleTo(""Test, Version"")] [assembly: InternalsVisibleTo(""app2, Retargetable=f"")] // CS1700 "; // Tested against Dev12 CreateCompilation(text).VerifyDiagnostics( // (8,12): warning CS1700: Assembly reference 'a'b'c' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""a'b'c"")").WithArguments("a'b'c").WithLocation(8, 12), // (9,12): warning CS1700: Assembly reference 'Test, PublicKey=Null' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, PublicKey=Null"")").WithArguments("Test, PublicKey=Null").WithLocation(9, 12), // (10,12): warning CS1700: Assembly reference 'Test, Bar' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Bar"")").WithArguments("Test, Bar").WithLocation(10, 12), // (11,12): warning CS1700: Assembly reference 'Test, Version' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""Test, Version"")").WithArguments("Test, Version").WithLocation(11, 12), // (12,12): warning CS1700: Assembly reference 'app2, Retargetable=f' is invalid and cannot be resolved Diagnostic(ErrorCode.WRN_InvalidAssemblyName, @"InternalsVisibleTo(""app2, Retargetable=f"")").WithArguments("app2, Retargetable=f").WithLocation(12, 12)); } // CS1701WRN_UnifyReferenceMajMin --> ReferenceManagerTests [Fact] public void CS1956WRN_MultipleRuntimeImplementationMatches() { var text = @"class Base<T, S> { public virtual int Test(out T x) // CS1956 { x = default(T); return 0; } public virtual int Test(ref S x) { return 1; } } interface IFace { int Test(out int x); } class Derived : Base<int, int>, IFace { static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_MultipleRuntimeImplementationMatches, Line = 20, Column = 33, IsWarning = true }); } [Fact] public void CS1957WRN_MultipleRuntimeOverrideMatches() { var text = @"class Base<TString> { public virtual void Test(TString s, out int x) { x = 0; } public virtual void Test(string s, ref int x) { } // CS1957 } class Derived : Base<string> { public override void Test(string s, ref int x) { } } "; // We no longer report a runtime ambiguous override (CS1957) because the compiler produces a methodimpl record to disambiguate. CSharpCompilation comp = CreateCompilation(text, targetFramework: TargetFramework.StandardLatest); Assert.Equal(RuntimeUtilities.IsCoreClrRuntime, comp.Assembly.RuntimeSupportsCovariantReturnsOfClasses); if (comp.Assembly.RuntimeSupportsDefaultInterfaceImplementation) { comp.VerifyDiagnostics( ); } else { comp.VerifyDiagnostics( // (8,25): warning CS1957: Member 'Derived.Test(string, ref int)' overrides 'Base<string>.Test(string, ref int)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. Please use a newer runtime. // public virtual void Test(string s, ref int x) { } // CS1957 Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "Test").WithArguments("Base<string>.Test(string, ref int)", "Derived.Test(string, ref int)").WithLocation(8, 25) ); } } [Fact] public void CS3000WRN_CLS_NoVarArgs() { var text = @" [assembly: System.CLSCompliant(true)] public class Test { public void AddABunchOfInts( __arglist) { } // CS3000 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): warning CS3000: Methods with variable arguments are not CLS-compliant // public void AddABunchOfInts( __arglist) { } // CS3000 Diagnostic(ErrorCode.WRN_CLS_NoVarArgs, "AddABunchOfInts")); } [Fact] public void CS3001WRN_CLS_BadArgType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public void bad(ushort i) // CS3001 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,28): warning CS3001: Argument type 'ushort' is not CLS-compliant // public void bad(ushort i) // CS3001 Diagnostic(ErrorCode.WRN_CLS_BadArgType, "i").WithArguments("ushort")); } [Fact] public void CS3002WRN_CLS_BadReturnType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort bad() // CS3002, public method { return ushort.MaxValue; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,19): warning CS3002: Return type of 'a.bad()' is not CLS-compliant // public ushort bad() // CS3002, public method Diagnostic(ErrorCode.WRN_CLS_BadReturnType, "bad").WithArguments("a.bad()")); } [Fact] public void CS3003WRN_CLS_BadFieldPropType() { var text = @"[assembly: System.CLSCompliant(true)] public class a { public ushort a1; // CS3003, public variable public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,19): warning CS3003: Type of 'a.a1' is not CLS-compliant // public ushort a1; // CS3003, public variable Diagnostic(ErrorCode.WRN_CLS_BadFieldPropType, "a1").WithArguments("a.a1")); } [Fact] public void CS3005WRN_CLS_BadIdentifierCase() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int a1 = 0; public static int A1 = 1; // CS3005 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,23): warning CS3005: Identifier 'a.A1' differing only in case is not CLS-compliant // public static int A1 = 1; // CS3005 Diagnostic(ErrorCode.WRN_CLS_BadIdentifierCase, "A1").WithArguments("a.A1")); } [Fact] public void CS3006WRN_CLS_OverloadRefOut() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyClass { public void f(int i) { } public void f(ref int i) // CS3006 { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (9,17): warning CS3006: Overloaded method 'MyClass.f(ref int)' differing only in ref or out, or in array rank, is not CLS-compliant // public void f(ref int i) // CS3006 Diagnostic(ErrorCode.WRN_CLS_OverloadRefOut, "f").WithArguments("MyClass.f(ref int)")); } [Fact] public void CS3007WRN_CLS_OverloadUnnamed() { var text = @"[assembly: System.CLSCompliant(true)] public struct S { public void F(int[][] array) { } public void F(byte[][] array) { } // CS3007 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,17): warning CS3007: Overloaded method 'S.F(byte[][])' differing only by unnamed array types is not CLS-compliant // public void F(byte[][] array) { } // CS3007 Diagnostic(ErrorCode.WRN_CLS_OverloadUnnamed, "F").WithArguments("S.F(byte[][])")); } [Fact] public void CS3008WRN_CLS_BadIdentifier() { var text = @"using System; [assembly: CLSCompliant(true)] public class a { public static int _a = 0; // CS3008 public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (5,23): warning CS3008: Identifier '_a' is not CLS-compliant // public static int _a = 0; // CS3008 Diagnostic(ErrorCode.WRN_CLS_BadIdentifier, "_a").WithArguments("_a")); } [Fact] public void CS3009WRN_CLS_BadBase() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class B { } public class C : B // CS3009 { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,14): warning CS3009: 'C': base type 'B' is not CLS-compliant // public class C : B // CS3009 Diagnostic(ErrorCode.WRN_CLS_BadBase, "C").WithArguments("C", "B")); } [Fact] public void CS3010WRN_CLS_BadInterfaceMember() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I { [CLSCompliant(false)] int M(); // CS3010 } public class C : I { public int M() { return 1; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,9): warning CS3010: 'I.M()': CLS-compliant interfaces must have only CLS-compliant members // int M(); // CS3010 Diagnostic(ErrorCode.WRN_CLS_BadInterfaceMember, "M").WithArguments("I.M()")); } [Fact] public void CS3011WRN_CLS_NoAbstractMembers() { var text = @"using System; [assembly: CLSCompliant(true)] public abstract class I { [CLSCompliant(false)] public abstract int M(); // CS3011 } public class C : I { public override int M() { return 1; } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,25): warning CS3011: 'I.M()': only CLS-compliant members can be abstract // public abstract int M(); // CS3011 Diagnostic(ErrorCode.WRN_CLS_NoAbstractMembers, "M").WithArguments("I.M()")); } [Fact] public void CS3012WRN_CLS_NotOnModules() { var text = @"[module: System.CLSCompliant(true)] // CS3012 public class C { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (1,10): warning CS3012: You must specify the CLSCompliant attribute on the assembly, not the module, to enable CLS compliance checking // [module: System.CLSCompliant(true)] // CS3012 Diagnostic(ErrorCode.WRN_CLS_NotOnModules, "System.CLSCompliant(true)")); } [Fact] public void CS3013WRN_CLS_ModuleMissingCLS() { var netModule = CreateEmptyCompilation("", options: TestOptions.ReleaseModule, assemblyName: "lib").EmitToImageReference(expectedWarnings: new[] { Diagnostic(ErrorCode.WRN_NoRuntimeMetadataVersion) }); CreateCompilation("[assembly: System.CLSCompliant(true)]", new[] { netModule }).VerifyDiagnostics( // lib.netmodule: warning CS3013: Added modules must be marked with the CLSCompliant attribute to match the assembly Diagnostic(ErrorCode.WRN_CLS_ModuleMissingCLS)); } [Fact] public void CS3014WRN_CLS_AssemblyNotCLS() { var text = @"using System; // [assembly:CLSCompliant(true)] public class I { [CLSCompliant(true)] // CS3014 public void M() { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,17): warning CS3014: 'I.M()' cannot be marked as CLS-compliant because the assembly does not have a CLSCompliant attribute // public void M() Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS, "M").WithArguments("I.M()")); } [Fact] public void CS3015WRN_CLS_BadAttributeType() { var text = @"using System; [assembly: CLSCompliant(true)] public class MyAttribute : Attribute { public MyAttribute(int[] ai) { } // CS3015 } "; CreateCompilation(text).VerifyDiagnostics( // (4,14): warning CS3015: 'MyAttribute' has no accessible constructors which use only CLS-compliant types // public class MyAttribute : Attribute Diagnostic(ErrorCode.WRN_CLS_BadAttributeType, "MyAttribute").WithArguments("MyAttribute")); } [Fact] public void CS3016WRN_CLS_ArrayArgumentToAttribute() { var text = @"using System; [assembly: CLSCompliant(true)] [C(new int[] { 1, 2 })] // CS3016 public class C : Attribute { public C() { } public C(int[] a) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,2): warning CS3016: Arrays as attribute arguments is not CLS-compliant // [C(new int[] { 1, 2 })] // CS3016 Diagnostic(ErrorCode.WRN_CLS_ArrayArgumentToAttribute, "C(new int[] { 1, 2 })")); } [Fact] public void CS3017WRN_CLS_NotOnModules2() { var text = @"using System; [module: CLSCompliant(true)] [assembly: CLSCompliant(false)] // CS3017 class C { static void Main() { } } "; // NOTE: unlike dev11, roslyn assumes that [assembly:CLSCompliant(false)] means // "suppress all CLS diagnostics". CreateCompilation(text).VerifyDiagnostics(); } [Fact] public void CS3018WRN_CLS_IllegalTrueInFalse() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(false)] public class Outer { [CLSCompliant(true)] // CS3018 public class Nested { } [CLSCompliant(false)] public class Nested3 { } } "; CreateCompilation(text).VerifyDiagnostics( // (7,18): warning CS3018: 'Outer.Nested' cannot be marked as CLS-compliant because it is a member of non-CLS-compliant type 'Outer' // public class Nested { } Diagnostic(ErrorCode.WRN_CLS_IllegalTrueInFalse, "Nested").WithArguments("Outer.Nested", "Outer")); } [Fact] public void CS3019WRN_CLS_MeaninglessOnPrivateType() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] // CS3019 class C { [CLSCompliant(false)] // CS3019 void Test() { } static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (4,7): warning CS3019: CLS compliance checking will not be performed on 'C' because it is not visible from outside this assembly // class C Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "C").WithArguments("C"), // (7,10): warning CS3019: CLS compliance checking will not be performed on 'C.Test()' because it is not visible from outside this assembly // void Test() Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnPrivateType, "Test").WithArguments("C.Test()")); } [Fact] public void CS3021WRN_CLS_AssemblyNotCLS2() { var text = @"using System; [CLSCompliant(false)] // CS3021 public class C { public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (3,14): warning CS3021: 'C' does not need a CLSCompliant attribute because the assembly does not have a CLSCompliant attribute // public class C Diagnostic(ErrorCode.WRN_CLS_AssemblyNotCLS2, "C").WithArguments("C")); } [Fact] public void CS3022WRN_CLS_MeaninglessOnParam() { var text = @"using System; [assembly: CLSCompliant(true)] [CLSCompliant(true)] public class C { public void F([CLSCompliant(true)] int i) { } public static void Main() { } } "; CreateCompilation(text).VerifyDiagnostics( // (6,20): warning CS3022: CLSCompliant attribute has no meaning when applied to parameters. Try putting it on the method instead. // public void F([CLSCompliant(true)] int i) Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnParam, "CLSCompliant(true)")); } [Fact] public void CS3023WRN_CLS_MeaninglessOnReturn() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { [return: System.CLSCompliant(true)] // CS3023 public static int Main() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (4,14): warning CS3023: CLSCompliant attribute has no meaning when applied to return types. Try putting it on the method instead. // [return: System.CLSCompliant(true)] // CS3023 Diagnostic(ErrorCode.WRN_CLS_MeaninglessOnReturn, "System.CLSCompliant(true)")); } [Fact] public void CS3024WRN_CLS_BadTypeVar() { var text = @"[assembly: System.CLSCompliant(true)] [type: System.CLSCompliant(false)] public class TestClass // CS3024 { public ushort us; } [type: System.CLSCompliant(false)] public interface ITest // CS3024 { } public interface I<T> where T : TestClass { } public class TestClass_2<T> where T : ITest { } public class TestClass_3<T> : I<T> where T : TestClass { } public class TestClass_4<T> : TestClass_2<T> where T : ITest { } public class Test { public static int Main() { return 0; } } "; CreateCompilation(text).VerifyDiagnostics( // (11,20): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public interface I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass"), // (13,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (17,26): warning CS3024: Constraint type 'ITest' is not CLS-compliant // public class TestClass_4<T> : TestClass_2<T> where T : ITest Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("ITest"), // (15,26): warning CS3024: Constraint type 'TestClass' is not CLS-compliant // public class TestClass_3<T> : I<T> where T : TestClass Diagnostic(ErrorCode.WRN_CLS_BadTypeVar, "T").WithArguments("TestClass")); } [Fact] public void CS3026WRN_CLS_VolatileField() { var text = @"[assembly: System.CLSCompliant(true)] public class Test { public volatile int v0 = 0; // CS3026 public static void Main() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_VolatileField, Line = 4, Column = 25, IsWarning = true }); } [Fact] public void CS3027WRN_CLS_BadInterface() { var text = @"using System; [assembly: CLSCompliant(true)] public interface I1 { } [CLSCompliant(false)] public interface I2 { } public interface I : I1, I2 { } public class Goo { static void Main() { } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.WRN_CLS_BadInterface, Line = 13, Column = 18, IsWarning = true }); } #endregion #region "Regressions or Mixed errors" [Fact] // bug 1985 public void ConstructWithErrors() { var text = @" class Base<T>{} class Derived : Base<NotFound>{}"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 22 }); var derived = comp.SourceModule.GlobalNamespace.GetTypeMembers("Derived").Single(); var Base = derived.BaseType(); Assert.Equal(TypeKind.Class, Base.TypeKind); } [Fact] // bug 3045 public void AliasQualifiedName00() { var text = @"using NSA = A; namespace A { class Goo { } } namespace B { class Test { class NSA { public NSA(int Goo) { this.Goo = Goo; } int Goo; } static int Main() { NSA::Goo goo = new NSA::Goo(); // shouldn't error here goo = Xyzzy; return 0; } static NSA::Goo Xyzzy = null; // shouldn't error here } }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; var test = b.GetMembers("Test").Single() as NamedTypeSymbol; var nsa = test.GetMembers("NSA").Single() as NamedTypeSymbol; Assert.Equal(2, nsa.GetMembers().Length); } [WorkItem(538218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538218")] [Fact] public void RecursiveInterfaceLookup01() { var text = @"interface A<T> { } interface B : A<B.Garbage> { }"; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DottedTypeNameNotFoundInAgg, Line = 2, Column = 19 }); var b = comp.SourceModule.GlobalNamespace.GetMembers("B").Single() as NamespaceSymbol; } [WorkItem(538150, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538150")] [Fact] public void CS0102ERR_DuplicateNameInClass04() { var text = @" namespace NS { struct MyType { public class MyMeth { } public void MyMeth() { } public int MyMeth; } } "; var comp = CreateCompilation(text).VerifyDiagnostics( // (8,21): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public void MyMeth() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): error CS0102: The type 'NS.MyType' already contains a definition for 'MyMeth' // public int MyMeth; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "MyMeth").WithArguments("NS.MyType", "MyMeth"), // (9,20): warning CS0649: Field 'NS.MyType.MyMeth' is never assigned to, and will always have its default value 0 // public int MyMeth; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "MyMeth").WithArguments("NS.MyType.MyMeth", "0") ); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type1 = ns.GetMembers("MyType").Single() as NamedTypeSymbol; Assert.Equal(4, type1.GetMembers().Length); // constructor included } [Fact] public void CS0102ERR_DuplicateNameInClass05() { CreateCompilation( @"class C { void P() { } int P { get { return 0; } } object Q { get; set; } void Q(int x, int y) { } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(4, 9), Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "Q").WithLocation(6, 10)); } [Fact] public void CS0102ERR_DuplicateNameInClass06() { CreateCompilation( @"class C { private double get_P; // CS0102 private int set_P { get { return 0; } } // CS0102 void get_Q(object o) { } // no error class set_Q { } // CS0102 public int P { get; set; } object Q { get { return null; } } object R { set { } } enum get_R { } // CS0102 struct set_R { } // CS0102 }") .VerifyDiagnostics( // (7,20): error CS0102: The type 'C' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("C", "get_P"), // (7,25): error CS0102: The type 'C' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_P"), // (8,12): error CS0102: The type 'C' already contains a definition for 'set_Q' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Q").WithArguments("C", "set_Q"), // (9,12): error CS0102: The type 'C' already contains a definition for 'get_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "R").WithArguments("C", "get_R"), // (9,16): error CS0102: The type 'C' already contains a definition for 'set_R' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("C", "set_R"), // (3,20): warning CS0169: The field 'C.get_P' is never used // private double get_P; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("C.get_P")); } [Fact] public void CS0102ERR_DuplicateNameInClass07() { CreateCompilation( @"class C { public int P { get { return 0; } set { } } public bool P { get { return false; } } }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "P").WithArguments("C", "P").WithLocation(8, 17)); } [WorkItem(538616, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538616")] [Fact] public void CS0102ERR_DuplicateNameInClass08() { var text = @" class A<T> { void T() { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 10 }); } [WorkItem(538917, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538917")] [Fact] public void CS0102ERR_DuplicateNameInClass09() { var text = @" class A<T> { class T<S> { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_DuplicateNameInClass, Line = 4, Column = 11 }); } [WorkItem(538634, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538634")] [Fact] public void CS0102ERR_DuplicateNameInClass10() { var text = @"class C<A, B, D, E, F, G> { object A; void B() { } object D { get; set; } class E { } struct F { } enum G { } }"; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (3,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'A' // object A; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "A").WithArguments("C<A, B, D, E, F, G>", "A"), // (4,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'B' // void B() { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "B").WithArguments("C<A, B, D, E, F, G>", "B"), // (5,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'D' // object D { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C<A, B, D, E, F, G>", "D"), // (6,11): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'E' // class E { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C<A, B, D, E, F, G>", "E"), // (7,12): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'F' // struct F { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C<A, B, D, E, F, G>", "F"), // (8,10): error CS0102: The type 'C<A, B, D, E, F, G>' already contains a definition for 'G' // enum G { } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C<A, B, D, E, F, G>", "G"), // (3,12): warning CS0169: The field 'C<A, B, D, E, F, G>.A' is never used // object A; Diagnostic(ErrorCode.WRN_UnreferencedField, "A").WithArguments("C<A, B, D, E, F, G>.A")); } [Fact] public void CS0101ERR_DuplicateNameInNS05() { CreateCompilation( @"namespace N { enum E { A, B } enum E { A } // CS0101 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "E").WithArguments("E", "N").WithLocation(4, 10)); } [WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")] [Fact] public void CS0101ERR_DuplicateNameInNS06() { CreateCompilation( @"namespace N { interface I { int P { get; } object Q { get; } } interface I // CS0101 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0101 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0101 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0101: The namespace 'N' already contains a definition for 'I' // interface I // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "I").WithArguments("I", "N"), // (17,12): error CS0101: The namespace 'N' already contains a definition for 'S' // struct S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (22,11): error CS0101: The namespace 'N' already contains a definition for 'S' // class S // CS0101 Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "S").WithArguments("S", "N"), // (27,18): error CS0101: The namespace 'N' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "D").WithArguments("D", "N"), // (24,16): warning CS0169: The field 'N.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("N.S.T"), // (20,13): warning CS0169: The field 'N.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("N.S.I") ); } [WorkItem(539742, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539742")] [Fact] public void CS0102ERR_DuplicateNameInClass11() { CreateCompilation( @"class C { enum E { A, B } enum E { A } // CS0102 }") .VerifyDiagnostics( Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "E").WithLocation(4, 10)); } [WorkItem(528149, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528149")] [Fact] public void CS0102ERR_DuplicateNameInClass12() { CreateCompilation( @"class C { interface I { int P { get; } object Q { get; } } interface I // CS0102 { object Q { get; set; } } struct S { class T { } interface I { } } struct S // CS0102 { struct T { } // Dev10 reports CS0102 for T! int I; } class S // CS0102 { object T; } delegate void D(); delegate int D(int i); }") .VerifyDiagnostics( // (8,15): error CS0102: The type 'C' already contains a definition for 'I' // interface I // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "I").WithArguments("C", "I"), // (17,12): error CS0102: The type 'C' already contains a definition for 'S' // struct S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (22,11): error CS0102: The type 'C' already contains a definition for 'S' // class S // CS0102 Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "S").WithArguments("C", "S"), // (27,18): error CS0102: The type 'C' already contains a definition for 'D' // delegate int D(int i); Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "D").WithArguments("C", "D"), // (24,16): warning CS0169: The field 'C.S.T' is never used // object T; Diagnostic(ErrorCode.WRN_UnreferencedField, "T").WithArguments("C.S.T"), // (20,13): warning CS0169: The field 'C.S.I' is never used // int I; Diagnostic(ErrorCode.WRN_UnreferencedField, "I").WithArguments("C.S.I") ); } [Fact] public void CS0102ERR_DuplicateNameInClass13() { CreateCompilation( @"class C { private double add_E; // CS0102 private event System.Action remove_E; // CS0102 void add_F(object o) { } // no error class remove_F { } // CS0102 public event System.Action E; event System.Action F; event System.Action G; enum add_G { } // CS0102 struct remove_G { } // CS0102 }") .VerifyDiagnostics( // (72): error CS0102: The type 'C' already contains a definition for 'add_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "add_E"), // (72): error CS0102: The type 'C' already contains a definition for 'remove_E' // public event System.Action E; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "E").WithArguments("C", "remove_E"), // (8,25): error CS0102: The type 'C' already contains a definition for 'remove_F' // event System.Action F; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "F").WithArguments("C", "remove_F"), // (9,25): error CS0102: The type 'C' already contains a definition for 'add_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "add_G"), // (9,25): error CS0102: The type 'C' already contains a definition for 'remove_G' // event System.Action G; Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "G").WithArguments("C", "remove_G"), // (8,25): warning CS0067: The event 'C.F' is never used // event System.Action F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("C.F"), // (3,20): warning CS0169: The field 'C.add_E' is never used // private double add_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedField, "add_E").WithArguments("C.add_E"), // (4,33): warning CS0067: The event 'C.remove_E' is never used // private event System.Action remove_E; // CS0102 Diagnostic(ErrorCode.WRN_UnreferencedEvent, "remove_E").WithArguments("C.remove_E"), // (72): warning CS0067: The event 'C.E' is never used // public event System.Action E; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E").WithArguments("C.E"), // (9,25): warning CS0067: The event 'C.G' is never used // event System.Action G; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "G").WithArguments("C.G")); } [Fact] public void CS0102ERR_DuplicateNameInClass14() { var text = @"using System.Runtime.CompilerServices; interface I { object this[object index] { get; set; } void Item(); } struct S { [IndexerName(""P"")] object this[object index] { get { return null; } } object Item; // no error object P; } class A { object get_Item; object set_Item; object this[int x, int y] { set { } } } class B { [IndexerName(""P"")] object this[object index] { get { return null; } } object get_Item; // no error object get_P; } class A1 { internal object this[object index] { get { return null; } } } class A2 { internal object Item; // no error } class B1 : A1 { internal object Item; } class B2 : A2 { internal object this[object index] { get { return null; } } // no error }"; CreateCompilation(text).VerifyDiagnostics( // (4,12): error CS0102: The type 'I' already contains a definition for 'Item' // object this[object index] { get; set; } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("I", "Item"), // (10,12): error CS0102: The type 'S' already contains a definition for 'P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("S", "P"), // (18,12): error CS0102: The type 'A' already contains a definition for 'get_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (18,33): error CS0102: The type 'A' already contains a definition for 'set_Item' // object this[int x, int y] { set { } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (23,33): error CS0102: The type 'B' already contains a definition for 'get_P' // object this[object index] { get { return null; } } Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "get").WithArguments("B", "get_P"), // (11,12): warning CS0169: The field 'S.Item' is never used // object Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("S.Item"), // (12,12): warning CS0169: The field 'S.P' is never used // object P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("S.P"), // (16,12): warning CS0169: The field 'A.get_Item' is never used // object get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item"), // (17,12): warning CS0169: The field 'A.set_Item' is never used // object set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item"), // (24,12): warning CS0169: The field 'B.get_Item' is never used // object get_Item; // no error Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("B.get_Item"), // (25,12): warning CS0169: The field 'B.get_P' is never used // object get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("B.get_P"), // (33,21): warning CS0649: Field 'A2.Item' is never assigned to, and will always have its default value null // internal object Item; // no error Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("A2.Item", "null"), // (37,21): warning CS0649: Field 'B1.Item' is never assigned to, and will always have its default value null // internal object Item; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Item").WithArguments("B1.Item", "null") ); } // Indexers without IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass15() { var template = @" class A {{ public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilation(string.Format(template, "int Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item"), // (5,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); // Error even though the indexer doesn't have a getter CreateCompilation(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_Item"), // (5,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilation(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_Item"), // (5,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); // Error even though the signatures don't match CreateCompilation(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'Item' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "Item")); // Since the signatures don't match CreateCompilation(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } // Indexers with IndexerNameAttribute [Fact] public void CS0102ERR_DuplicateNameInClass16() { var template = @" using System.Runtime.CompilerServices; class A {{ [IndexerName(""P"")] public int this[int x] {{ set {{ }} }} {0} }}"; CreateCompilation(string.Format(template, "int P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P"), // (7,9): warning CS0169: The field 'A.P' is never used // int P; Diagnostic(ErrorCode.WRN_UnreferencedField, "P").WithArguments("A.P")); // Error even though the indexer doesn't have a getter CreateCompilation(string.Format(template, "int get_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'get_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "get_P"), // (7,9): warning CS0169: The field 'A.get_P' is never used // int get_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_P").WithArguments("A.get_P")); CreateCompilation(string.Format(template, "int set_P;")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'set_P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "set").WithArguments("A", "set_P"), // (7,9): warning CS0169: The field 'A.set_P' is never used // int set_P; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_P").WithArguments("A.set_P")); // Error even though the signatures don't match CreateCompilation(string.Format(template, "int P() { return 0; }")).VerifyDiagnostics( // (4,16): error CS0102: The type 'A' already contains a definition for 'P' Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "this").WithArguments("A", "P")); // Since the signatures don't match CreateCompilation(string.Format(template, "int set_P() { return 0; }")).VerifyDiagnostics(); // No longer have issues with "Item" names CreateCompilation(string.Format(template, "int Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.Item' is never used // int Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "Item").WithArguments("A.Item")); CreateCompilation(string.Format(template, "int get_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.get_Item' is never used // int get_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "get_Item").WithArguments("A.get_Item")); CreateCompilation(string.Format(template, "int set_Item;")).VerifyDiagnostics( // (7,9): warning CS0169: The field 'A.set_Item' is never used // int set_Item; Diagnostic(ErrorCode.WRN_UnreferencedField, "set_Item").WithArguments("A.set_Item")); CreateCompilation(string.Format(template, "int Item() { return 0; }")).VerifyDiagnostics(); CreateCompilation(string.Format(template, "int set_Item() { return 0; }")).VerifyDiagnostics(); } [WorkItem(539625, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539625")] [Fact] public void CS0104ERR_AmbigContext02() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I<string>.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I<A1> { public static int Method() { return 1; } } namespace LevelThree { public class I<A1> { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [Fact] public void CS0104ERR_AmbigContext03() { var text = @" namespace Conformance.Expressions { using LevelOne.LevelTwo; using LevelOne.LevelTwo.LevelThree; public class Test { public static int Main() { return I.Method(); // CS0104 } } namespace LevelOne { namespace LevelTwo { public class I { public static int Method() { return 1; } } namespace LevelThree { public class I { public static int Method() { return 2; } } } } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_AmbigContext, Line = 12, Column = 20 }); } [WorkItem(540255, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540255")] [Fact] public void CS0122ERR_BadAccess01() { var text = @" interface I<T> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Goo(new A.C()); } static void Goo<T>(I<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 15, Column = 9 }); } [Fact] public void CS0122ERR_BadAccess02() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { static void Main() { Goo(new A.C()); } static void Goo<T>(I<T> x) { } static void Goo<T>(J<T> x) { } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); // no errors } [Fact] public void CS0122ERR_BadAccess03() { var text = @" interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { System.Console.WriteLine(""I""); } // static void M<T>(J<T> c) // { // System.Console.WriteLine(""J""); // } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_BadAccess, Line = 29, Column = 15 }); } [Fact] public void CS0122ERR_BadAccess04() { var text = @"using System; interface J<T> { } interface I<T> : J<object> { } class A { private class B { } public class C : I<B> { } } class Program { delegate void D(A.C x); static void M<T>(I<T> c) { Console.WriteLine(""I""); } static void M<T>(J<T> c) { Console.WriteLine(""J""); } static void Main() { D d = M; d(null); } } "; var comp = DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text); } [WorkItem(3202, "DevDiv_Projects/Roslyn")] [Fact] public void CS0246ERR_SingleTypeNameNotFound_InaccessibleImport() { var text = @"using A = A; namespace X { using B; } static class A { private static class B { } }"; CreateCompilation(text).VerifyDiagnostics( // (4,11): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // using B; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(4, 11), // (1,1): info CS8019: Unnecessary using directive. // using A = A; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using A = A;").WithLocation(1, 1), // (4,5): info CS8019: Unnecessary using directive. // using B; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using B;").WithLocation(4, 5)); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_1() { var text = @"class ClassA { object F = new { f1<int> = 1 }; public static int f1 { get { return 1; } } } "; CreateCompilation(text).VerifyDiagnostics( // (3,22): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. // object F = new { f1<int> = 1 }; Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "f1<int> = 1").WithLocation(3, 22), // (3,22): error CS0307: The property 'ClassA.f1' cannot be used with type arguments // object F = new { f1<int> = 1 }; Diagnostic(ErrorCode.ERR_TypeArgsNotAllowed, "f1<int>").WithArguments("ClassA.f1", "property").WithLocation(3, 22)); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_2() { var text = @"class ClassA { object F = new { f1<T> }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_SingleTypeNameNotFound, Line = 3, Column = 25 }, new ErrorDescription { Code = (int)ErrorCode.ERR_TypeArgsNotAllowed, Line = 3, Column = 22 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_3() { var text = @"class ClassA { object F = new { f1+ }; public static int f1 { get { return 1; } } } "; DiagnosticsUtils.VerifyErrorsAndGetCompilationWithMscorlib(text, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, Line = 3, Column = 22 }, new ErrorDescription { Code = (int)ErrorCode.ERR_InvalidExprTerm, Line = 3, Column = 26 } ); } [Fact] public void CS0746ERR_InvalidAnonymousTypeMemberDeclarator_4() { var text = @"class ClassA { object F = new { f1<int> }; public static int f1<T>() { return 1; } } "; CreateCompilation(text).VerifyDiagnostics( // (3,22): error CS0746: Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access. // object F = new { f1<int> }; Diagnostic(ErrorCode.ERR_InvalidAnonymousTypeMemberDeclarator, "f1<int>").WithLocation(3, 22), // (3,22): error CS0828: Cannot assign method group to anonymous type property // object F = new { f1<int> }; Diagnostic(ErrorCode.ERR_AnonymousTypePropertyAssignedBadValue, "f1<int>").WithArguments("method group").WithLocation(3, 22)); } [Fact] public void CS7025ERR_BadVisEventType() { var text = @"internal interface InternalInterface { } internal delegate void InternalDelegate(); public class PublicClass { protected class Protected { } public event System.Action<InternalInterface> A; public event System.Action<InternalClass> B; internal event System.Action<Protected> C; public event InternalDelegate D; public event InternalDelegate E { add { } remove { } } } internal class InternalClass : PublicClass { public event System.Action<Protected> F; } "; CreateCompilation(text).VerifyDiagnostics( // (9,51): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalInterface>' is less accessible than event 'PublicClass.A' // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.ERR_BadVisEventType, "A").WithArguments("PublicClass.A", "System.Action<InternalInterface>"), // (10,47): error CS7025: Inconsistent accessibility: event type 'System.Action<InternalClass>' is less accessible than event 'PublicClass.B' // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.ERR_BadVisEventType, "B").WithArguments("PublicClass.B", "System.Action<InternalClass>"), // (11,45): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'PublicClass.C' // internal event System.Action<Protected> C; Diagnostic(ErrorCode.ERR_BadVisEventType, "C").WithArguments("PublicClass.C", "System.Action<PublicClass.Protected>"), // (13,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.D' // public event InternalDelegate D; Diagnostic(ErrorCode.ERR_BadVisEventType, "D").WithArguments("PublicClass.D", "InternalDelegate"), // (14,35): error CS7025: Inconsistent accessibility: event type 'InternalDelegate' is less accessible than event 'PublicClass.E' // public event InternalDelegate E { add { } remove { } } Diagnostic(ErrorCode.ERR_BadVisEventType, "E").WithArguments("PublicClass.E", "InternalDelegate"), // (18,43): error CS7025: Inconsistent accessibility: event type 'System.Action<PublicClass.Protected>' is less accessible than event 'InternalClass.F' // public event System.Action<Protected> F; Diagnostic(ErrorCode.ERR_BadVisEventType, "F").WithArguments("InternalClass.F", "System.Action<PublicClass.Protected>"), // (9,51): warning CS0067: The event 'PublicClass.A' is never used // public event System.Action<InternalInterface> A; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "A").WithArguments("PublicClass.A"), // (10,47): warning CS0067: The event 'PublicClass.B' is never used // public event System.Action<InternalClass> B; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "B").WithArguments("PublicClass.B"), // (11,45): warning CS0067: The event 'PublicClass.C' is never used // internal event System.Action<Protected> C; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "C").WithArguments("PublicClass.C"), // (13,35): warning CS0067: The event 'PublicClass.D' is never used // public event InternalDelegate D; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "D").WithArguments("PublicClass.D"), // (18,43): warning CS0067: The event 'InternalClass.F' is never used // public event System.Action<Protected> F; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "F").WithArguments("InternalClass.F")); } [Fact, WorkItem(543386, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543386")] public void VolatileFieldWithGenericTypeConstrainedToClass() { var text = @" public class C {} class G<T> where T : C { public volatile T Fld = default(T); } "; CreateCompilation(text).VerifyDiagnostics(); } #endregion [WorkItem(7920, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/7920")] [Fact()] public void Bug7920() { var comp1 = CreateCompilation(@" public class MyAttribute1 : System.Attribute {} ", options: TestOptions.ReleaseDll, assemblyName: "Bug7920_CS"); var comp2 = CreateCompilation(@" public class MyAttribute2 : MyAttribute1 {} ", new[] { new CSharpCompilationReference(comp1) }, options: TestOptions.ReleaseDll); var expected = new[] { // (2,2): error CS0012: The type 'MyAttribute1' is defined in an assembly that is not referenced. You must add a reference to assembly 'Bug7920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [MyAttribute2] Diagnostic(ErrorCode.ERR_NoTypeDef, "MyAttribute2").WithArguments("MyAttribute1", "Bug7920_CS, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null") }; var source3 = @" [MyAttribute2] public class Test {} "; var comp3 = CreateCompilation(source3, new[] { new CSharpCompilationReference(comp2) }, options: TestOptions.ReleaseDll); comp3.GetDiagnostics().Verify(expected); var comp4 = CreateCompilation(source3, new[] { comp2.EmitToImageReference() }, options: TestOptions.ReleaseDll); comp4.GetDiagnostics().Verify(expected); } [Fact, WorkItem(345, "https://github.com/dotnet/roslyn")] public void InferredStaticTypeArgument() { var source = @"class Program { static void Main(string[] args) { M(default(C)); } public static void M<T>(T t) { } } static class C { }"; CreateCompilation(source).VerifyDiagnostics( // (5,9): error CS0718: 'C': static types cannot be used as type arguments // M(default(C)); Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "M").WithArguments("C").WithLocation(5, 9) ); } [Fact, WorkItem(511, "https://github.com/dotnet/roslyn")] public void StaticTypeArgumentOfDynamicInvocation() { var source = @"static class S {} class C { static void M() { dynamic d1 = 123; d1.N<S>(); // The dev11 compiler does not diagnose this } static void Main() {} }"; CreateCompilation(source).VerifyDiagnostics(); } [Fact] public void AbstractInScript() { var source = @"internal abstract void M(); internal abstract object P { get; } internal abstract event System.EventHandler E;"; var compilation = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Script, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (1,24): error CS0513: 'M()' is abstract but it is contained in non-abstract type 'Script' // internal abstract void M(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M").WithArguments("M()", "Script").WithLocation(1, 24), // (2,30): error CS0513: 'P.get' is abstract but it is contained in non-abstract type 'Script' // internal abstract object P { get; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("P.get", "Script").WithLocation(2, 30), // (3,45): error CS0513: 'E' is abstract but it is contained in non-abstract type 'Script' // internal abstract event System.EventHandler E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("E", "Script").WithLocation(3, 45)); } [WorkItem(529225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529225")] [Fact] public void AbstractInSubmission() { var references = new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }; var source = @"internal abstract void M(); internal abstract object P { get; } internal abstract event System.EventHandler E;"; var submission = CSharpCompilation.CreateScriptCompilation("s0.dll", SyntaxFactory.ParseSyntaxTree(source, options: TestOptions.Script), new[] { MscorlibRef_v4_0_30316_17626, SystemCoreRef }); submission.VerifyDiagnostics( // (1,24): error CS0513: 'M()' is abstract but it is contained in non-abstract type 'Script' // internal abstract void M(); Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "M").WithArguments("M()", "Script").WithLocation(1, 24), // (2,30): error CS0513: 'P.get' is abstract but it is contained in non-abstract type 'Script' // internal abstract object P { get; } Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "get").WithArguments("P.get", "Script").WithLocation(2, 30), // (3,45): error CS0513: 'E' is abstract but it is contained in non-abstract type 'Script' // internal abstract event System.EventHandler E; Diagnostic(ErrorCode.ERR_AbstractInConcreteClass, "E").WithArguments("E", "Script").WithLocation(3, 45)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsOfATypeToDifferentAssembliesWithoutUsingItShouldNotReportAnError() { var forwardingIL = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) .ver 4:0:0:0 } .assembly Forwarding { } .module Forwarding.dll .assembly extern Destination1 { } .assembly extern Destination2 { } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 } .class public auto ansi beforefieldinit TestSpace.ExistingReference extends [mscorlib]System.Object { .field public static literal string Value = ""TEST VALUE"" .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void[mscorlib] System.Object::.ctor() IL_0006: nop IL_0007: ret } }"; var ilReference = CompileIL(forwardingIL, prependDefaultHeader: false); var code = @" using TestSpace; namespace UserSpace { public class Program { public static void Main() { System.Console.WriteLine(ExistingReference.Value); } } }"; CompileAndVerify( source: code, references: new MetadataReference[] { ilReference }, expectedOutput: "TEST VALUE"); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsOfFullyQualifiedTypeToDifferentAssembliesWhileReferencingItShouldErrorOut() { var userCode = @" namespace ForwardingNamespace { public class Program { public static void Main() { new Destination.TestClass(); } } }"; var forwardingIL = @" .assembly extern Destination1 { .ver 1:0:0:0 } .assembly extern Destination2 { .ver 1:0:0:0 } .assembly Forwarder { .ver 1:0:0:0 } .module ForwarderModule.dll .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 }"; var compilation = CreateCompilationWithILAndMscorlib40(userCode, forwardingIL, appendDefaultHeader: false); compilation.VerifyDiagnostics( // (8,29): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestClass").WithArguments("ForwarderModule.dll", "Forwarder, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination.TestClass", "Destination1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 29), // (8,29): error CS0234: The type or namespace name 'TestClass' does not exist in the namespace 'Destination' (are you missing an assembly reference?) // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestClass").WithArguments("TestClass", "Destination").WithLocation(8, 29)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsToManyAssembliesShouldJustReportTheFirstTwo() { var userCode = @" namespace ForwardingNamespace { public class Program { public static void Main() { new Destination.TestClass(); } } }"; var forwardingIL = @" .assembly Forwarder { } .module ForwarderModule.dll .assembly extern Destination1 { } .assembly extern Destination2 { } .assembly extern Destination3 { } .assembly extern Destination4 { } .assembly extern Destination5 { } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 } .class extern forwarder Destination.TestClass { .assembly extern Destination3 } .class extern forwarder Destination.TestClass { .assembly extern Destination4 } .class extern forwarder Destination.TestClass { .assembly extern Destination5 } .class extern forwarder Destination.TestClass { .assembly extern Destination1 } .class extern forwarder Destination.TestClass { .assembly extern Destination2 }"; var compilation = CreateCompilationWithILAndMscorlib40(userCode, forwardingIL, appendDefaultHeader: false); compilation.VerifyDiagnostics( // (8,29): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Destination.TestClass' to multiple assemblies: 'Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestClass").WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination.TestClass", "Destination1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Destination2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 29), // (8,29): error CS0234: The type or namespace name 'TestClass' does not exist in the namespace 'Destination' (are you missing an assembly reference?) // new Destination.TestClass(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestClass").WithArguments("TestClass", "Destination").WithLocation(8, 29)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void RequiredExternalTypesForAMethodSignatureWillReportErrorsIfForwardedToMultipleAssemblies() { // The scenario is that assembly A is calling a method from assembly B. This method has a parameter of a type that lives // in assembly C. If A is compiled against B and C, it should compile successfully. // Now if assembly C is replaced with assembly C2, that forwards the type to both D1 and D2, it should fail with the appropriate error. var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static void MethodB(ClassC obj) { System.Console.WriteLine(obj.GetHashCode()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeA = @" using B; namespace A { public class ClassA { public void MethodA() { ClassB.MethodB(null); } } }"; CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC }, assemblyName: "A").VerifyDiagnostics(); // No Errors var codeC2 = @" .assembly C { } .module CModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder C.ClassC { .assembly extern D1 } .class extern forwarder C.ClassC { .assembly extern D2 }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2 }, assemblyName: "A").VerifyDiagnostics( // (10,13): error CS8329: Module 'CModule.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // ClassB.MethodB(null); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "ClassB.MethodB").WithArguments("CModule.dll", "C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C.ClassC", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10332")] [WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleTypeForwardersToTheSameAssemblyShouldNotResultInMultipleForwardError() { var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static string MethodB(ClassC obj) { return ""obj is "" + (obj == null ? ""null"" : obj.ToString()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeA = @" using B; namespace A { public class ClassA { public static void Main() { System.Console.WriteLine(ClassB.MethodB(null)); } } }"; CompileAndVerify( source: codeA, references: new MetadataReference[] { referenceB, referenceC }, expectedOutput: "obj is null"); var codeC2 = @" .assembly C { .ver 0:0:0:0 } .assembly extern D { } .class extern forwarder C.ClassC { .assembly extern D } .class extern forwarder C.ClassC { .assembly extern D }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2 }).VerifyDiagnostics( // (10,38): error CS0012: The type 'ClassC' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // System.Console.WriteLine(ClassB.MethodB(null)); Diagnostic(ErrorCode.ERR_NoTypeDef, "ClassB.MethodB").WithArguments("C.ClassC", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(10, 38)); var codeD = @" namespace C { public class ClassC { } }"; var referenceD = CreateCompilation(codeD, assemblyName: "D").EmitToImageReference(); CompileAndVerify( source: codeA, references: new MetadataReference[] { referenceB, referenceC2, referenceD }, expectedOutput: "obj is null"); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void CompilingModuleWithMultipleForwardersToDifferentAssembliesShouldErrorOut() { var ilSource = @" .module ForwarderModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var ilModule = GetILModuleReference(ilSource, prependDefaultHeader: false); CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule }, assemblyName: "Forwarder").VerifyDiagnostics( // error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies).WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void CompilingModuleWithMultipleForwardersToTheSameAssemblyShouldNotProduceMultipleForwardingErrors() { var ilSource = @" .assembly extern D { } .class extern forwarder Testspace.TestType { .assembly extern D } .class extern forwarder Testspace.TestType { .assembly extern D }"; var ilModule = GetILModuleReference(ilSource, prependDefaultHeader: false); CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule }).VerifyDiagnostics( // error CS0012: The type 'TestType' is defined in an assembly that is not referenced. You must add a reference to assembly 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Diagnostic(ErrorCode.ERR_NoTypeDef).WithArguments("Testspace.TestType", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(1, 1)); var dCode = @" namespace Testspace { public class TestType { } }"; var dReference = CreateCompilation(dCode, assemblyName: "D").EmitToImageReference(); // Now compilation succeeds CreateCompilation(string.Empty, references: new MetadataReference[] { ilModule, dReference }).VerifyDiagnostics(); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void LookingUpATypeForwardedTwiceInASourceCompilationReferenceShouldFail() { // This test specifically tests that SourceAssembly symbols also produce this error (by using a CompilationReference instead of the usual PEAssembly symbol) var ilSource = @" .module ForwarderModule.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var ilModuleReference = GetILModuleReference(ilSource, prependDefaultHeader: false); var forwarderCompilation = CreateEmptyCompilation( source: string.Empty, references: new MetadataReference[] { ilModuleReference }, options: TestOptions.DebugDll, assemblyName: "Forwarder"); var csSource = @" namespace UserSpace { public class UserClass { public static void Main() { var obj = new Testspace.TestType(); } } }"; var userCompilation = CreateCompilation( source: csSource, references: new MetadataReference[] { forwarderCompilation.ToMetadataReference() }, assemblyName: "UserAssembly"); userCompilation.VerifyDiagnostics( // (8,37): error CS8329: Module 'ForwarderModule.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestType").WithArguments("ForwarderModule.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(8, 37), // (8,37): error CS0234: The type or namespace name 'TestType' does not exist in the namespace 'Testspace' (are you missing an assembly reference?) // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType").WithArguments("TestType", "Testspace").WithLocation(8, 37)); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void ForwardingErrorsInLaterModulesAlwaysOverwriteOnesInEarlierModules() { var module1IL = @" .module module1IL.dll .assembly extern D1 { } .assembly extern D2 { } .class extern forwarder Testspace.TestType { .assembly extern D1 } .class extern forwarder Testspace.TestType { .assembly extern D2 }"; var module1Reference = GetILModuleReference(module1IL, prependDefaultHeader: false); var module2IL = @" .module module12L.dll .assembly extern D3 { } .assembly extern D4 { } .class extern forwarder Testspace.TestType { .assembly extern D3 } .class extern forwarder Testspace.TestType { .assembly extern D4 }"; var module2Reference = GetILModuleReference(module2IL, prependDefaultHeader: false); var forwarderCompilation = CreateEmptyCompilation( source: string.Empty, references: new MetadataReference[] { module1Reference, module2Reference }, options: TestOptions.DebugDll, assemblyName: "Forwarder"); var csSource = @" namespace UserSpace { public class UserClass { public static void Main() { var obj = new Testspace.TestType(); } } }"; var userCompilation = CreateCompilation( source: csSource, references: new MetadataReference[] { forwarderCompilation.ToMetadataReference() }, assemblyName: "UserAssembly"); userCompilation.VerifyDiagnostics( // (8,37): error CS8329: Module 'module12L.dll' in assembly 'Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'Testspace.TestType' to multiple assemblies: 'D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "TestType").WithArguments("module12L.dll", "Forwarder, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "Testspace.TestType", "D3, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "D4, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"), // (8,37): error CS0234: The type or namespace name 'TestType' does not exist in the namespace 'Testspace' (are you missing an assembly reference?) // var obj = new Testspace.TestType(); Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "TestType").WithArguments("TestType", "Testspace")); } [Fact, WorkItem(16484, "https://github.com/dotnet/roslyn/issues/16484")] public void MultipleForwardsThatChainResultInTheSameAssemblyShouldStillProduceAnError() { // The scenario is that assembly A is calling a method from assembly B. This method has a parameter of a type that lives // in assembly C. Now if assembly C is replaced with assembly C2, that forwards the type to both D and E, and D forwards it to E, // it should fail with the appropriate error. var codeC = @" namespace C { public class ClassC {} }"; var referenceC = CreateCompilation(codeC, assemblyName: "C").EmitToImageReference(); var codeB = @" using C; namespace B { public static class ClassB { public static void MethodB(ClassC obj) { System.Console.WriteLine(obj.GetHashCode()); } } }"; var referenceB = CreateCompilation(codeB, references: new MetadataReference[] { referenceC }, assemblyName: "B").EmitToImageReference(); var codeC2 = @" .assembly C { } .module C.dll .assembly extern D { } .assembly extern E { } .class extern forwarder C.ClassC { .assembly extern D } .class extern forwarder C.ClassC { .assembly extern E }"; var referenceC2 = CompileIL(codeC2, prependDefaultHeader: false); var codeD = @" .assembly D { } .assembly extern E { } .class extern forwarder C.ClassC { .assembly extern E }"; var referenceD = CompileIL(codeD, prependDefaultHeader: false); var referenceE = CreateCompilation(codeC, assemblyName: "E").EmitToImageReference(); var codeA = @" using B; using C; namespace A { public class ClassA { public void MethodA(ClassC obj) { ClassB.MethodB(obj); } } }"; CreateCompilation(codeA, references: new MetadataReference[] { referenceB, referenceC2, referenceD, referenceE }, assemblyName: "A").VerifyDiagnostics( // (11,13): error CS8329: Module 'C.dll' in assembly 'C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is forwarding the type 'C.ClassC' to multiple assemblies: 'D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // ClassB.MethodB(obj); Diagnostic(ErrorCode.ERR_TypeForwardedToMultipleAssemblies, "ClassB.MethodB").WithArguments("C.dll", "C, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "C.ClassC", "D, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "E, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(11, 13)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithRef() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithIn() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(in int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_NoneWithOut() { CreateCompilation(@" partial class C { partial void M(int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithNone() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithIn() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(in int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_RefWithOut() { CreateCompilation(@" partial class C { partial void M(ref int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithNone() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithRef() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_InWithOut() { CreateCompilation(@" partial class C { partial void M(in int i); partial void M(out int i) { i = 0; } }").VerifyDiagnostics( // (4,18): error CS8795: Partial method 'C.M(out int)' must have accessibility modifiers because it has 'out' parameters. // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(4, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(out int)' // partial void M(out int i) { i = 0; } Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(out int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithNone() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(int)' // partial void M(int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithRef() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(ref int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(ref int)' // partial void M(ref int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(ref int)").WithLocation(4, 18)); } [Fact] public void PartialMethodsConsiderRefKindDifferences_OutWithIn() { CreateCompilation(@" partial class C { partial void M(out int i); partial void M(in int i) {} }").VerifyDiagnostics( // (3,18): error CS8794: Partial method C.M(out int) must have an implementation part because it has 'out' parameters. // partial void M(out int i); Diagnostic(ErrorCode.ERR_PartialMethodWithOutParamMustHaveAccessMods, "M").WithArguments("C.M(out int)").WithLocation(3, 18), // (4,18): error CS0759: No defining declaration found for implementing declaration of partial method 'C.M(in int)' // partial void M(in int i) {} Diagnostic(ErrorCode.ERR_PartialMethodMustHaveLatent, "M").WithArguments("C.M(in int)").WithLocation(4, 18)); } [Fact] public void MethodWithNoReturnTypeShouldNotComplainAboutStaticCtor() { CreateCompilation(@" class X { private static Y(int i) {} }").VerifyDiagnostics( // (4,20): error CS1520: Method must have a return type // private static Y(int i) {} Diagnostic(ErrorCode.ERR_MemberNeedsType, "Y").WithLocation(4, 20)); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpErrorListNetCore.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListNetCore : CSharpErrorListCommon { public CSharpErrorListNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorList() { base.ErrorList(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Microsoft.VisualStudio.IntegrationTest.Utilities.Common.ProjectUtils; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpErrorListNetCore : CSharpErrorListCommon { public CSharpErrorListNetCore(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, WellKnownProjectTemplates.CSharpNetCoreClassLibrary) { } public override async Task InitializeAsync() { await base.InitializeAsync().ConfigureAwait(false); // The CSharpNetCoreClassLibrary template does not open a file automatically. VisualStudio.SolutionExplorer.OpenFile(new Project(ProjectName), WellKnownProjectTemplates.CSharpNetCoreClassLibraryClassFileName); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorList() { base.ErrorList(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorLevelWarning() { base.ErrorLevelWarning(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] public override void ErrorsDuringMethodBodyEditing() { base.ErrorsDuringMethodBodyEditing(); } [WpfFact] [Trait(Traits.Feature, Traits.Features.ErrorList)] [Trait(Traits.Feature, Traits.Features.NetCore)] [WorkItem(39902, "https://github.com/dotnet/roslyn/issues/39902")] public override void ErrorsAfterClosingFile() { base.ErrorsAfterClosingFile(); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/CSharpTest/InvertIf/InvertIfTests.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.CSharp.InvertIf; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InvertIf { public partial class InvertIfTests : AbstractCSharpCodeActionTest { private async Task TestFixOneAsync( string initial, string expected) { await TestInRegularAndScriptAsync(CreateTreeText(initial), CreateTreeText(expected)); } protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInvertIfCodeRefactoringProvider(); private static string CreateTreeText(string initial) { return @"class A { bool a = true; bool b = true; bool c = true; bool d = true; void Goo() { " + initial + @" } }"; } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Identifier() { await TestFixOneAsync( @"[||]if (a) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/!a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifier() { await TestFixOneAsync( @"[||]if (!a) { a(); } else { b(); }", @"if (a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/!/*1b*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_EqualsEquals() { await TestFixOneAsync( @"[||]if (a == b) { a(); } else { b(); }", @"if (a != b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotEquals() { await TestFixOneAsync( @"[||]if (a != b) { a(); } else { b(); }", @"if (a == b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThan() { await TestFixOneAsync( @"[||]if (a > b) { a(); } else { b(); }", @"if (a <= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThanEquals() { await TestFixOneAsync( @"[||]if (a >= b) { a(); } else { b(); }", @"if (a < b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThan() { await TestFixOneAsync( @"[||]if (a < b) { a(); } else { b(); }", @"if (a >= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThanEquals() { await TestFixOneAsync( @"[||]if (a <= b) { a(); } else { b(); }", @"if (a > b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParentheses() { await TestFixOneAsync( @"[||]if ((a)) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/26427"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithInnerTrivia() { await TestFixOneAsync( @"[||]if ((/*1*/a/*2*/)) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithMiddleTrivia() { await TestFixOneAsync( @"[||]if (/*1*/(a)/*2*/) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithOutsideTrivia() { await TestFixOneAsync( @"[||]if /*before*/((a))/*after*/ { a(); } else { b(); }", @"if /*before*/(!a)/*after*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Is() { await TestFixOneAsync( @"[||]if (a is Goo) { a(); } else { b(); }", @"if (a is not Goo) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_MethodCall() { await TestFixOneAsync( @"[||]if (a.Goo()) { a(); } else { b(); }", @"if (!a.Goo()) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or() { await TestFixOneAsync( @"[||]if (a || b) { a(); } else { b(); }", @"if (!a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or2() { await TestFixOneAsync( @"[||]if (!a || !b) { a(); } else { b(); }", @"if (a && b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or3() { await TestFixOneAsync( @"[||]if (!a || b) { a(); } else { b(); }", @"if (a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or4() { await TestFixOneAsync( @"[||]if (a | b) { a(); } else { b(); }", @"if (!a & !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And() { await TestFixOneAsync( @"[||]if (a && b) { a(); } else { b(); }", @"if (!a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And2() { await TestFixOneAsync( @"[||]if (!a && !b) { a(); } else { b(); }", @"if (a || b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And3() { await TestFixOneAsync( @"[||]if (!a && b) { a(); } else { b(); }", @"if (a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And4() { await TestFixOneAsync( @"[||]if (a & b) { a(); } else { b(); }", @"if (!a | !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_ParenthesizeAndForPrecedence() { await TestFixOneAsync( @"[||]if (a && b || c) { a(); } else { b(); }", @"if ((!a || !b) && !c) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Plus() { await TestFixOneAsync( @"[||]if (a + b) { a(); } else { b(); }", @"if (!(a + b)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_True() { await TestFixOneAsync( @"[||]if (true) { a(); } else { b(); }", @"if (false) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueWithTrivia() { await TestFixOneAsync( @"[||]if (/*1*/true/*2*/) { a(); } else { b(); }", @"if (/*1*/false/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_False() { await TestFixOneAsync( @"[||]if (false) { a(); } else { b(); }", @"if (true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_OtherLiteralExpression() { await TestFixOneAsync( @"[||]if (literalexpression) { a(); } else { b(); }", @"if (!literalexpression) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueAndFalse() { await TestFixOneAsync( @"[||]if (true && false) { a(); } else { b(); }", @"if (false || true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NoCurlyBraces() { await TestFixOneAsync( @"[||]if (a) a(); else b();", @"if (!a) b(); else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else b();", @"if (!a) b(); else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnElse() { await TestFixOneAsync( @"[||]if (a) a(); else { b(); }", @"if (!a) { b(); } else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); }", @"if (!a) { if (b) { b(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIfElse() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); } else { c(); }", @"if (!a) { if (b) { b(); } else { c(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CompoundConditional() { await TestFixOneAsync( @"[||]if (((a == b) && (c != d)) || ((e < f) && (!g))) { a(); } else { b(); }", @"if ((a != b || c == d) && (e >= f || g)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Trivia() { await TestFixOneAsync( @"[||]if /*1*/ (a) /*2*/ { /*3*/ a() /*4*/; /*5*/ } /*6*/ else if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*15*/", @"if /*1*/ (!a) /*2*/ { if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*6*/ } else { /*3*/ a() /*4*/; /*5*/ } /*15*/"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression_BrokenCode() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression() { await TestInRegularAndScriptAsync( @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a) { a(); } else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection1() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); } else if (b) { b(); } else { c(); }|] } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection2() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); }|] else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultilineMissing_IfElseIfElseSubSelection() { await TestMissingInRegularAndScriptAsync( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) bar(); else if (baz) Quux(); } }", @"class A { void Goo() { if (!foo) { if (baz) Quux(); } else bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_OpenCloseBracesSameLine() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) { x(); x(); } else { y(); y(); } } }", @"class A { void Goo() { if (!foo) { y(); y(); } else { x(); x(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_Trivia() { await TestInRegularAndScriptAsync( @"class A { void Goo() { /*1*/ [||]if (a) /*2*/ { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ else if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ /*20*/ } }", @"class A { void Goo() { /*1*/ if (!a) /*2*/ { if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ } else { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ /*20*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition1() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { #line hidden [||]if (a) { a(); } else { b(); } #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition2() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); #line default } else { b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition3() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); } else { #line hidden b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition4() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); } else { b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition5() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); #line hidden } else { #line default b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition6() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } } }", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition7() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } #line hidden } } #line default", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string[] x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero3() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0x0) { a(); } else { b(); } } } ", @"string x; if (x.Length == 0x0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero4() { await TestFixOneAsync( @"string x; [||]if (0 < x.Length) { a(); } else { b(); } } } ", @"string x; if (0 == x.Length) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero1() { await TestFixOneAsync( @"byte x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"byte x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero2() { await TestFixOneAsync( @"ushort x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"ushort x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero3() { await TestFixOneAsync( @"uint x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"uint x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero4() { await TestFixOneAsync( @"ulong x = 1; [||]if (x > 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x == 0) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero1() { await TestFixOneAsync( @"ulong x = 1; [||]if (0 == x) { a(); } else { b(); } } } ", @"ulong x = 1; if (0 != x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero2() { await TestFixOneAsync( @"ulong x = 1; [||]if (x == 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x != 0) { b(); } else { a(); } } } "); } [WorkItem(530505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyLongLengthEqualsZero() { await TestFixOneAsync( @"string[] x; [||]if (x.LongLength > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.LongLength == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length >= 0) { a(); } else { b(); } } } ", @"string x; if (x.Length < 0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0.0f) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length <= 0.0f) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(29434, "https://github.com/dotnet/roslyn/issues/29434")] public async Task TestIsExpression() { await TestInRegularAndScriptAsync( @"class C { void M(object o) { [||]if (o is C) { a(); } else { } } }", @"class C { void M(object o) { if (o is not C) { } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestEmptyIf() { await TestInRegularAndScriptAsync( @"class C { void M(string s){ [||]if (s == ""a""){}else{ s = ""b""}}}", @"class C { void M(string s){ if (s != ""a""){ s = ""b""}}}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlySingleLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { // A single line comment } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { // A single line comment } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlyMultilineLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { /* * This is * a multiline * comment with * two words * per line. */ } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { /* * This is * a multiline * comment with * two words * per line. */ } } }"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.InvertIf; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.InvertIf { public partial class InvertIfTests : AbstractCSharpCodeActionTest { private async Task TestFixOneAsync( string initial, string expected) { await TestInRegularAndScriptAsync(CreateTreeText(initial), CreateTreeText(expected)); } protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpInvertIfCodeRefactoringProvider(); private static string CreateTreeText(string initial) { return @"class A { bool a = true; bool b = true; bool c = true; bool d = true; void Goo() { " + initial + @" } }"; } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Identifier() { await TestFixOneAsync( @"[||]if (a) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/!a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifier() { await TestFixOneAsync( @"[||]if (!a) { a(); } else { b(); }", @"if (a) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotIdentifierWithTrivia() { await TestFixOneAsync( @"[||]if /*0*/(/*1*/!/*1b*/a/*2*/)/*3*/ { a(); } else { b(); }", @"if /*0*/(/*1*/a/*2*/)/*3*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_EqualsEquals() { await TestFixOneAsync( @"[||]if (a == b) { a(); } else { b(); }", @"if (a != b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NotEquals() { await TestFixOneAsync( @"[||]if (a != b) { a(); } else { b(); }", @"if (a == b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThan() { await TestFixOneAsync( @"[||]if (a > b) { a(); } else { b(); }", @"if (a <= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_GreaterThanEquals() { await TestFixOneAsync( @"[||]if (a >= b) { a(); } else { b(); }", @"if (a < b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThan() { await TestFixOneAsync( @"[||]if (a < b) { a(); } else { b(); }", @"if (a >= b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_LessThanEquals() { await TestFixOneAsync( @"[||]if (a <= b) { a(); } else { b(); }", @"if (a > b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParentheses() { await TestFixOneAsync( @"[||]if ((a)) { a(); } else { b(); }", @"if (!a) { b(); } else { a(); }"); } [WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/26427"), Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithInnerTrivia() { await TestFixOneAsync( @"[||]if ((/*1*/a/*2*/)) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithMiddleTrivia() { await TestFixOneAsync( @"[||]if (/*1*/(a)/*2*/) { a(); } else { b(); }", @"if (/*1*/!a/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoubleParenthesesWithOutsideTrivia() { await TestFixOneAsync( @"[||]if /*before*/((a))/*after*/ { a(); } else { b(); }", @"if /*before*/(!a)/*after*/ { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Is() { await TestFixOneAsync( @"[||]if (a is Goo) { a(); } else { b(); }", @"if (a is not Goo) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_MethodCall() { await TestFixOneAsync( @"[||]if (a.Goo()) { a(); } else { b(); }", @"if (!a.Goo()) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or() { await TestFixOneAsync( @"[||]if (a || b) { a(); } else { b(); }", @"if (!a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or2() { await TestFixOneAsync( @"[||]if (!a || !b) { a(); } else { b(); }", @"if (a && b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or3() { await TestFixOneAsync( @"[||]if (!a || b) { a(); } else { b(); }", @"if (a && !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Or4() { await TestFixOneAsync( @"[||]if (a | b) { a(); } else { b(); }", @"if (!a & !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And() { await TestFixOneAsync( @"[||]if (a && b) { a(); } else { b(); }", @"if (!a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And2() { await TestFixOneAsync( @"[||]if (!a && !b) { a(); } else { b(); }", @"if (a || b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And3() { await TestFixOneAsync( @"[||]if (!a && b) { a(); } else { b(); }", @"if (a || !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_And4() { await TestFixOneAsync( @"[||]if (a & b) { a(); } else { b(); }", @"if (!a | !b) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_ParenthesizeAndForPrecedence() { await TestFixOneAsync( @"[||]if (a && b || c) { a(); } else { b(); }", @"if ((!a || !b) && !c) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Plus() { await TestFixOneAsync( @"[||]if (a + b) { a(); } else { b(); }", @"if (!(a + b)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_True() { await TestFixOneAsync( @"[||]if (true) { a(); } else { b(); }", @"if (false) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueWithTrivia() { await TestFixOneAsync( @"[||]if (/*1*/true/*2*/) { a(); } else { b(); }", @"if (/*1*/false/*2*/) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_False() { await TestFixOneAsync( @"[||]if (false) { a(); } else { b(); }", @"if (true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_OtherLiteralExpression() { await TestFixOneAsync( @"[||]if (literalexpression) { a(); } else { b(); }", @"if (!literalexpression) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_TrueAndFalse() { await TestFixOneAsync( @"[||]if (true && false) { a(); } else { b(); }", @"if (false || true) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_NoCurlyBraces() { await TestFixOneAsync( @"[||]if (a) a(); else b();", @"if (!a) b(); else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else b();", @"if (!a) b(); else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CurlyBracesOnElse() { await TestFixOneAsync( @"[||]if (a) a(); else { b(); }", @"if (!a) { b(); } else a();"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIf() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); }", @"if (!a) { if (b) { b(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_IfElseIfElse() { await TestFixOneAsync( @"[||]if (a) { a(); } else if (b) { b(); } else { c(); }", @"if (!a) { if (b) { b(); } else { c(); } } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_CompoundConditional() { await TestFixOneAsync( @"[||]if (((a == b) && (c != d)) || ((e < f) && (!g))) { a(); } else { b(); }", @"if ((a != b || c == d) && (e >= f || g)) { b(); } else { a(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_Trivia() { await TestFixOneAsync( @"[||]if /*1*/ (a) /*2*/ { /*3*/ a() /*4*/; /*5*/ } /*6*/ else if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*15*/", @"if /*1*/ (!a) /*2*/ { if /*7*/ (b) /*8*/ { /*9*/ b(); /*10*/ } /*11*/ else /*12*/ { /*13*/ c(); /*14*/} /*6*/ } else { /*3*/ a() /*4*/; /*5*/ } /*15*/"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression_BrokenCode() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestKeepTriviaWithinExpression() { await TestInRegularAndScriptAsync( @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; [||]if (a || b && c < // comment d) { a(); } else { b(); } } }", @"class A { void Goo() { bool a = true; bool b = true; bool c = true; bool d = true; if (!a && (!b || c >= // comment d)) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (a) { a(); } else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection1() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); } else if (b) { b(); } else { c(); }|] } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElseIfElseSelection2() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [|if (a) { a(); }|] else if (b) { b(); } else { c(); } } }", @"class A { void Goo() { if (!a) { if (b) { b(); } else { c(); } } else { a(); } } }"); } [WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultilineMissing_IfElseIfElseSubSelection() { await TestMissingInRegularAndScriptAsync( @"class A { void Goo() { if (a) { a(); } [|else if (b) { b(); } else { c(); }|] } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_IfElse() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) bar(); else if (baz) Quux(); } }", @"class A { void Goo() { if (!foo) { if (baz) Quux(); } else bar(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_OpenCloseBracesSameLine() { await TestInRegularAndScriptAsync( @"class A { void Goo() { [||]if (foo) { x(); x(); } else { y(); y(); } } }", @"class A { void Goo() { if (!foo) { y(); y(); } else { x(); x(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestMultiline_Trivia() { await TestInRegularAndScriptAsync( @"class A { void Goo() { /*1*/ [||]if (a) /*2*/ { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ else if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ /*20*/ } }", @"class A { void Goo() { /*1*/ if (!a) /*2*/ { if (b) /*8*/ { /*9*/ /*10*/ goo(); /*11*/ /*12*/ } /*13*/ else /*14*/ { /*15*/ /*16*/ goo(); /*17*/ /*18*/ } /*19*/ } else { /*3*/ /*4*/ goo(); /*5*/ /*6*/ } /*7*/ /*20*/ } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition1() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { #line hidden [||]if (a) { a(); } else { b(); } #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition2() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); #line default } else { b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition3() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); } else { #line hidden b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition4() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { #line hidden a(); } else { b(); #line default } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition5() { await TestMissingInRegularAndScriptAsync( @"class C { void F() { [||]if (a) { a(); #line hidden } else { #line default b(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition6() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } } }", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestOverlapsHiddenPosition7() { await TestInRegularAndScriptAsync( @" #line hidden class C { void F() { #line default [||]if (a) { a(); } else { b(); } #line hidden } } #line default", @" #line hidden class C { void F() { #line default if (!a) { b(); } else { a(); } #line hidden } } #line default"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string[] x; [||]if (x.Length > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.Length == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero3() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0x0) { a(); } else { b(); } } } ", @"string x; if (x.Length == 0x0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToLengthEqualsZero4() { await TestFixOneAsync( @"string x; [||]if (0 < x.Length) { a(); } else { b(); } } } ", @"string x; if (0 == x.Length) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero1() { await TestFixOneAsync( @"byte x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"byte x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero2() { await TestFixOneAsync( @"ushort x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"ushort x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero3() { await TestFixOneAsync( @"uint x = 1; [||]if (0 < x) { a(); } else { b(); } } } ", @"uint x = 1; if (0 == x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToEqualsZero4() { await TestFixOneAsync( @"ulong x = 1; [||]if (x > 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x == 0) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero1() { await TestFixOneAsync( @"ulong x = 1; [||]if (0 == x) { a(); } else { b(); } } } ", @"ulong x = 1; if (0 != x) { b(); } else { a(); } } } "); } [WorkItem(545986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545986")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyToNotEqualsZero2() { await TestFixOneAsync( @"ulong x = 1; [||]if (x == 0) { a(); } else { b(); } } } ", @"ulong x = 1; if (x != 0) { b(); } else { a(); } } } "); } [WorkItem(530505, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_SimplifyLongLengthEqualsZero() { await TestFixOneAsync( @"string[] x; [||]if (x.LongLength > 0) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string[] x; if (x.LongLength == 0) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero() { await TestFixOneAsync( @"string x; [||]if (x.Length >= 0) { a(); } else { b(); } } } ", @"string x; if (x.Length < 0) { b(); } else { a(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] public async Task TestSingleLine_DoesNotSimplifyToLengthEqualsZero2() { await TestFixOneAsync( @"string x; [||]if (x.Length > 0.0f) { GreaterThanZero(); } else { EqualsZero(); } } } ", @"string x; if (x.Length <= 0.0f) { EqualsZero(); } else { GreaterThanZero(); } } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(29434, "https://github.com/dotnet/roslyn/issues/29434")] public async Task TestIsExpression() { await TestInRegularAndScriptAsync( @"class C { void M(object o) { [||]if (o is C) { a(); } else { } } }", @"class C { void M(object o) { if (o is not C) { } else { a(); } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestEmptyIf() { await TestInRegularAndScriptAsync( @"class C { void M(string s){ [||]if (s == ""a""){}else{ s = ""b""}}}", @"class C { void M(string s){ if (s != ""a""){ s = ""b""}}}"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlySingleLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { // A single line comment } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { // A single line comment } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInvertIf)] [WorkItem(43224, "https://github.com/dotnet/roslyn/issues/43224")] public async Task TestOnlyMultilineLineCommentIf() { await TestInRegularAndScriptAsync( @" class C { void M(string s) { [||]if (s == ""a"") { /* * This is * a multiline * comment with * two words * per line. */ } else { s = ""b"" } } }", @" class C { void M(string s) { if (s != ""a"") { s = ""b"" } else { /* * This is * a multiline * comment with * two words * per line. */ } } }"); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Collections/NormalizedTextSpanCollection.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.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared { internal class NormalizedTextSpanCollection : ReadOnlyCollection<TextSpan> { /// <summary> /// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that is /// empty. /// </summary> public NormalizedTextSpanCollection() : base(new List<TextSpan>(0)) { } /// <summary> /// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified span. /// </summary> /// <param name="span">TextSpan contained by the span set.</param> public NormalizedTextSpanCollection(TextSpan span) : base(ListFromSpan(span)) { } /// <summary> /// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified list of spans. /// </summary> /// <param name="spans">The spans to be added.</param> /// <remarks> /// <para>The list of spans will be sorted and normalized (overlapping and adjoining spans will be combined).</para> /// <para>This constructor runs in O(N log N) time, where N = spans.Count.</para></remarks> /// <exception cref="ArgumentNullException"><paramref name="spans"/> is null.</exception> public NormalizedTextSpanCollection(IEnumerable<TextSpan> spans) : base(NormalizedTextSpanCollection.NormalizeSpans(spans)) { // NormalizeSpans will throw if spans == null. } /// <summary> /// Finds the union of two span sets. /// </summary> /// <param name="left"> /// The first span set. /// </param> /// <param name="right"> /// The second span set. /// </param> /// <returns> /// The new span set that corresponds to the union of <paramref name="left"/> and <paramref name="right"/>. /// </returns> /// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks> /// <exception cref="ArgumentNullException">Either <paramref name="left"/> or <paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Union(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return right; } if (right.Count == 0) { return left; } var spans = new OrderedSpanList(); var index1 = 0; var index2 = 0; var start = -1; var end = int.MaxValue; while (index1 < left.Count && index2 < right.Count) { var span1 = left[index1]; var span2 = right[index2]; if (span1.Start < span2.Start) { NormalizedTextSpanCollection.UpdateSpanUnion(span1, spans, ref start, ref end); ++index1; } else { NormalizedTextSpanCollection.UpdateSpanUnion(span2, spans, ref start, ref end); ++index2; } } while (index1 < left.Count) { NormalizedTextSpanCollection.UpdateSpanUnion(left[index1], spans, ref start, ref end); ++index1; } while (index2 < right.Count) { NormalizedTextSpanCollection.UpdateSpanUnion(right[index2], spans, ref start, ref end); ++index2; } if (end != int.MaxValue) { spans.Add(TextSpan.FromBounds(start, end)); } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Finds the overlap of two span sets. /// </summary> /// <param name="left">The first span set.</param> /// <param name="right">The second span set.</param> /// <returns>The new span set that corresponds to the overlap of <paramref name="left"/> and <paramref name="right"/>.</returns> /// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks> /// <exception cref="ArgumentNullException"><paramref name="left"/> or <paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Overlap(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return left; } if (right.Count == 0) { return right; } var spans = new OrderedSpanList(); for (int index1 = 0, index2 = 0; index1 < left.Count && index2 < right.Count;) { var span1 = left[index1]; var span2 = right[index2]; if (span1.OverlapsWith(span2)) { spans.Add(span1.Overlap(span2)!.Value); } if (span1.End < span2.End) { ++index1; } else if (span1.End == span2.End) { ++index1; ++index2; } else { ++index2; } } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Finds the intersection of two span sets. /// </summary> /// <param name="left">The first span set.</param> /// <param name="right">The second span set.</param> /// <returns>The new span set that corresponds to the intersection of <paramref name="left"/> and <paramref name="right"/>.</returns> /// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks> /// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Intersection(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return left; } if (right.Count == 0) { return right; } var spans = new OrderedSpanList(); for (int index1 = 0, index2 = 0; (index1 < left.Count) && (index2 < right.Count);) { var span1 = left[index1]; var span2 = right[index2]; if (span1.IntersectsWith(span2)) { spans.Add(span1.Intersection(span2)!.Value); } if (span1.End < span2.End) { ++index1; } else { ++index2; } } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Finds the difference between two sets. The difference is defined as everything in the first span set that is not in the second span set. /// </summary> /// <param name="left">The first span set.</param> /// <param name="right">The second span set.</param> /// <returns>The new span set that corresponds to the difference between <paramref name="left"/> and <paramref name="right"/>.</returns> /// <remarks> /// Empty spans in the second set do not affect the first set at all. This method returns empty spans in the first set that are not contained by any set in /// the second set. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Difference(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return left; } if (right.Count == 0) { return left; } var spans = new OrderedSpanList(); var index1 = 0; var index2 = 0; var lastEnd = -1; do { var span1 = left[index1]; var span2 = right[index2]; if ((span2.Length == 0) || (span1.Start >= span2.End)) { ++index2; } else if (span1.End <= span2.Start) { // lastEnd is set to the end of the previously encountered intersecting span // from right when it ended before the end of span1 (so it must still be less // than the end of span1). Debug.Assert(lastEnd < span1.End); spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End)); ++index1; } else { // The spans intersect, so add anything from span1 that extends to the left of span2. if (span1.Start < span2.Start) { // lastEnd is set to the end of the previously encountered intersecting span // on span2, so it must be less than the start of the current span on span2. Debug.Assert(lastEnd < span2.Start); spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span2.Start)); } if (span1.End < span2.End) { ++index1; } else if (span1.End == span2.End) { // Both spans ended at the same place so we're done with both. ++index1; ++index2; } else { // span2 ends before span1, so keep track of where it ended so that we don't // try to add the excluded portion the next time we add a span. lastEnd = span2.End; ++index2; } } } while ((index1 < left.Count) && (index2 < right.Count)); while (index1 < left.Count) { var span1 = left[index1++]; spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End)); } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Determines whether two span sets are the same. /// </summary> /// <param name="left">The first set.</param> /// <param name="right">The second set.</param> /// <returns><c>true</c> if the two sets are equivalent, otherwise <c>false</c>.</returns> public static bool operator ==(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right) { if (object.ReferenceEquals(left, right)) { return true; } if (left is null || right is null) { return false; } if (left.Count != right.Count) { return false; } for (var i = 0; i < left.Count; ++i) { if (left[i] != right[i]) { return false; } } return true; } /// <summary> /// Determines whether two span sets are not the same. /// </summary> /// <param name="left">The first set.</param> /// <param name="right">The second set.</param> /// <returns><c>true</c> if the two sets are not equivalent, otherwise <c>false</c>.</returns> public static bool operator !=(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right) => !(left == right); /// <summary> /// Determines whether this span set overlaps with another span set. /// </summary> /// <param name="set">The span set to test.</param> /// <returns><c>true</c> if the span sets overlap, otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception> public bool OverlapsWith(NormalizedTextSpanCollection set) { if (set == null) { throw new ArgumentNullException(nameof(set)); } for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);) { var span1 = this[index1]; var span2 = set[index2]; if (span1.OverlapsWith(span2)) { return true; } if (span1.End < span2.End) { ++index1; } else if (span1.End == span2.End) { ++index1; ++index2; } else { ++index2; } } return false; } /// <summary> /// Determines whether this span set overlaps with another span. /// </summary> /// <param name="span">The span to test.</param> /// <returns><c>true</c> if this span set overlaps with the given span, otherwise <c>false</c>.</returns> public bool OverlapsWith(TextSpan span) { // TODO: binary search for (var index = 0; index < this.Count; ++index) { if (this[index].OverlapsWith(span)) { return true; } } return false; } /// <summary> /// Determines whether this span set intersects with another span set. /// </summary> /// <param name="set">Set to test.</param> /// <returns><c>true</c> if the span sets intersect, otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception> public bool IntersectsWith(NormalizedTextSpanCollection set) { if (set == null) { throw new ArgumentNullException(nameof(set)); } for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);) { var span1 = this[index1]; var span2 = set[index2]; if (span1.IntersectsWith(span2)) { return true; } if (span1.End < span2.End) { ++index1; } else { ++index2; } } return false; } /// <summary> /// Determines whether this span set intersects with another span. /// </summary> /// <returns><c>true</c> if this span set intersects with the given span, otherwise <c>false</c>.</returns> public bool IntersectsWith(TextSpan span) { // TODO: binary search for (var index = 0; index < this.Count; ++index) { if (this[index].IntersectsWith(span)) { return true; } } return false; } #region Overridden methods and operators /// <summary> /// Gets a unique hash code for the span set. /// </summary> /// <returns>A 32-bit hash code associated with the set.</returns> public override int GetHashCode() { var hc = 0; foreach (var s in this) { hc ^= s.GetHashCode(); } return hc; } /// <summary> /// Determines whether this span set is the same as another object. /// </summary> /// <param name="obj">The object to test.</param> /// <returns><c>true</c> if the two objects are equal, otherwise <c>false</c>.</returns> public override bool Equals(object? obj) { var set = obj as NormalizedTextSpanCollection; return this == set; } /// <summary> /// Provides a string representation of the set. /// </summary> /// <returns>The string representation of the set.</returns> public override string ToString() { var value = new StringBuilder("{"); foreach (var s in this) { value.Append(s.ToString()); } value.Append("}"); return value.ToString(); } #endregion // Overridden methods and operators #region Private Helpers private static IList<TextSpan> ListFromSpan(TextSpan span) { IList<TextSpan> list = new List<TextSpan>(1); list.Add(span); return list; } /// <summary> /// Private constructor for use when the span list is already normalized. /// </summary> /// <param name="normalizedSpans">An already normalized span list.</param> private NormalizedTextSpanCollection(OrderedSpanList normalizedSpans) : base(normalizedSpans) { } private static void UpdateSpanUnion(TextSpan span, IList<TextSpan> spans, ref int start, ref int end) { if (end < span.Start) { spans.Add(TextSpan.FromBounds(start, end)); start = -1; end = int.MaxValue; } if (end == int.MaxValue) { start = span.Start; end = span.End; } else { end = Math.Max(end, span.End); } } private static IList<TextSpan> NormalizeSpans(IEnumerable<TextSpan> spans) { if (spans == null) { throw new ArgumentNullException(nameof(spans)); } var sorted = new List<TextSpan>(spans); if (sorted.Count <= 1) { return sorted; } else { sorted.Sort(delegate (TextSpan s1, TextSpan s2) { return s1.Start.CompareTo(s2.Start); }); IList<TextSpan> normalized = new List<TextSpan>(sorted.Count); var oldStart = sorted[0].Start; var oldEnd = sorted[0].End; for (var i = 1; i < sorted.Count; ++i) { var newStart = sorted[i].Start; var newEnd = sorted[i].End; if (oldEnd < newStart) { normalized.Add(TextSpan.FromBounds(oldStart, oldEnd)); oldStart = newStart; oldEnd = newEnd; } else { oldEnd = Math.Max(oldEnd, newEnd); } } normalized.Add(TextSpan.FromBounds(oldStart, oldEnd)); return normalized; } } private class OrderedSpanList : List<TextSpan> { } #endregion // Private Helpers } }
// Licensed to the .NET Foundation under one or more 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.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Shared { internal class NormalizedTextSpanCollection : ReadOnlyCollection<TextSpan> { /// <summary> /// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that is /// empty. /// </summary> public NormalizedTextSpanCollection() : base(new List<TextSpan>(0)) { } /// <summary> /// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified span. /// </summary> /// <param name="span">TextSpan contained by the span set.</param> public NormalizedTextSpanCollection(TextSpan span) : base(ListFromSpan(span)) { } /// <summary> /// Initializes a new instance of <see cref="NormalizedTextSpanCollection"/> that contains the specified list of spans. /// </summary> /// <param name="spans">The spans to be added.</param> /// <remarks> /// <para>The list of spans will be sorted and normalized (overlapping and adjoining spans will be combined).</para> /// <para>This constructor runs in O(N log N) time, where N = spans.Count.</para></remarks> /// <exception cref="ArgumentNullException"><paramref name="spans"/> is null.</exception> public NormalizedTextSpanCollection(IEnumerable<TextSpan> spans) : base(NormalizedTextSpanCollection.NormalizeSpans(spans)) { // NormalizeSpans will throw if spans == null. } /// <summary> /// Finds the union of two span sets. /// </summary> /// <param name="left"> /// The first span set. /// </param> /// <param name="right"> /// The second span set. /// </param> /// <returns> /// The new span set that corresponds to the union of <paramref name="left"/> and <paramref name="right"/>. /// </returns> /// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks> /// <exception cref="ArgumentNullException">Either <paramref name="left"/> or <paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Union(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return right; } if (right.Count == 0) { return left; } var spans = new OrderedSpanList(); var index1 = 0; var index2 = 0; var start = -1; var end = int.MaxValue; while (index1 < left.Count && index2 < right.Count) { var span1 = left[index1]; var span2 = right[index2]; if (span1.Start < span2.Start) { NormalizedTextSpanCollection.UpdateSpanUnion(span1, spans, ref start, ref end); ++index1; } else { NormalizedTextSpanCollection.UpdateSpanUnion(span2, spans, ref start, ref end); ++index2; } } while (index1 < left.Count) { NormalizedTextSpanCollection.UpdateSpanUnion(left[index1], spans, ref start, ref end); ++index1; } while (index2 < right.Count) { NormalizedTextSpanCollection.UpdateSpanUnion(right[index2], spans, ref start, ref end); ++index2; } if (end != int.MaxValue) { spans.Add(TextSpan.FromBounds(start, end)); } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Finds the overlap of two span sets. /// </summary> /// <param name="left">The first span set.</param> /// <param name="right">The second span set.</param> /// <returns>The new span set that corresponds to the overlap of <paramref name="left"/> and <paramref name="right"/>.</returns> /// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks> /// <exception cref="ArgumentNullException"><paramref name="left"/> or <paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Overlap(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return left; } if (right.Count == 0) { return right; } var spans = new OrderedSpanList(); for (int index1 = 0, index2 = 0; index1 < left.Count && index2 < right.Count;) { var span1 = left[index1]; var span2 = right[index2]; if (span1.OverlapsWith(span2)) { spans.Add(span1.Overlap(span2)!.Value); } if (span1.End < span2.End) { ++index1; } else if (span1.End == span2.End) { ++index1; ++index2; } else { ++index2; } } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Finds the intersection of two span sets. /// </summary> /// <param name="left">The first span set.</param> /// <param name="right">The second span set.</param> /// <returns>The new span set that corresponds to the intersection of <paramref name="left"/> and <paramref name="right"/>.</returns> /// <remarks>This operator runs in O(N+M) time where N = left.Count, M = right.Count.</remarks> /// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Intersection(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return left; } if (right.Count == 0) { return right; } var spans = new OrderedSpanList(); for (int index1 = 0, index2 = 0; (index1 < left.Count) && (index2 < right.Count);) { var span1 = left[index1]; var span2 = right[index2]; if (span1.IntersectsWith(span2)) { spans.Add(span1.Intersection(span2)!.Value); } if (span1.End < span2.End) { ++index1; } else { ++index2; } } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Finds the difference between two sets. The difference is defined as everything in the first span set that is not in the second span set. /// </summary> /// <param name="left">The first span set.</param> /// <param name="right">The second span set.</param> /// <returns>The new span set that corresponds to the difference between <paramref name="left"/> and <paramref name="right"/>.</returns> /// <remarks> /// Empty spans in the second set do not affect the first set at all. This method returns empty spans in the first set that are not contained by any set in /// the second set. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="left"/> is null.</exception> /// <exception cref="ArgumentNullException"><paramref name="right"/> is null.</exception> public static NormalizedTextSpanCollection Difference(NormalizedTextSpanCollection left, NormalizedTextSpanCollection right) { if (left == null) { throw new ArgumentNullException(nameof(left)); } if (right == null) { throw new ArgumentNullException(nameof(right)); } if (left.Count == 0) { return left; } if (right.Count == 0) { return left; } var spans = new OrderedSpanList(); var index1 = 0; var index2 = 0; var lastEnd = -1; do { var span1 = left[index1]; var span2 = right[index2]; if ((span2.Length == 0) || (span1.Start >= span2.End)) { ++index2; } else if (span1.End <= span2.Start) { // lastEnd is set to the end of the previously encountered intersecting span // from right when it ended before the end of span1 (so it must still be less // than the end of span1). Debug.Assert(lastEnd < span1.End); spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End)); ++index1; } else { // The spans intersect, so add anything from span1 that extends to the left of span2. if (span1.Start < span2.Start) { // lastEnd is set to the end of the previously encountered intersecting span // on span2, so it must be less than the start of the current span on span2. Debug.Assert(lastEnd < span2.Start); spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span2.Start)); } if (span1.End < span2.End) { ++index1; } else if (span1.End == span2.End) { // Both spans ended at the same place so we're done with both. ++index1; ++index2; } else { // span2 ends before span1, so keep track of where it ended so that we don't // try to add the excluded portion the next time we add a span. lastEnd = span2.End; ++index2; } } } while ((index1 < left.Count) && (index2 < right.Count)); while (index1 < left.Count) { var span1 = left[index1++]; spans.Add(TextSpan.FromBounds(Math.Max(lastEnd, span1.Start), span1.End)); } return new NormalizedTextSpanCollection(spans); } /// <summary> /// Determines whether two span sets are the same. /// </summary> /// <param name="left">The first set.</param> /// <param name="right">The second set.</param> /// <returns><c>true</c> if the two sets are equivalent, otherwise <c>false</c>.</returns> public static bool operator ==(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right) { if (object.ReferenceEquals(left, right)) { return true; } if (left is null || right is null) { return false; } if (left.Count != right.Count) { return false; } for (var i = 0; i < left.Count; ++i) { if (left[i] != right[i]) { return false; } } return true; } /// <summary> /// Determines whether two span sets are not the same. /// </summary> /// <param name="left">The first set.</param> /// <param name="right">The second set.</param> /// <returns><c>true</c> if the two sets are not equivalent, otherwise <c>false</c>.</returns> public static bool operator !=(NormalizedTextSpanCollection? left, NormalizedTextSpanCollection? right) => !(left == right); /// <summary> /// Determines whether this span set overlaps with another span set. /// </summary> /// <param name="set">The span set to test.</param> /// <returns><c>true</c> if the span sets overlap, otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception> public bool OverlapsWith(NormalizedTextSpanCollection set) { if (set == null) { throw new ArgumentNullException(nameof(set)); } for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);) { var span1 = this[index1]; var span2 = set[index2]; if (span1.OverlapsWith(span2)) { return true; } if (span1.End < span2.End) { ++index1; } else if (span1.End == span2.End) { ++index1; ++index2; } else { ++index2; } } return false; } /// <summary> /// Determines whether this span set overlaps with another span. /// </summary> /// <param name="span">The span to test.</param> /// <returns><c>true</c> if this span set overlaps with the given span, otherwise <c>false</c>.</returns> public bool OverlapsWith(TextSpan span) { // TODO: binary search for (var index = 0; index < this.Count; ++index) { if (this[index].OverlapsWith(span)) { return true; } } return false; } /// <summary> /// Determines whether this span set intersects with another span set. /// </summary> /// <param name="set">Set to test.</param> /// <returns><c>true</c> if the span sets intersect, otherwise <c>false</c>.</returns> /// <exception cref="ArgumentNullException"><paramref name="set"/> is null.</exception> public bool IntersectsWith(NormalizedTextSpanCollection set) { if (set == null) { throw new ArgumentNullException(nameof(set)); } for (int index1 = 0, index2 = 0; (index1 < this.Count) && (index2 < set.Count);) { var span1 = this[index1]; var span2 = set[index2]; if (span1.IntersectsWith(span2)) { return true; } if (span1.End < span2.End) { ++index1; } else { ++index2; } } return false; } /// <summary> /// Determines whether this span set intersects with another span. /// </summary> /// <returns><c>true</c> if this span set intersects with the given span, otherwise <c>false</c>.</returns> public bool IntersectsWith(TextSpan span) { // TODO: binary search for (var index = 0; index < this.Count; ++index) { if (this[index].IntersectsWith(span)) { return true; } } return false; } #region Overridden methods and operators /// <summary> /// Gets a unique hash code for the span set. /// </summary> /// <returns>A 32-bit hash code associated with the set.</returns> public override int GetHashCode() { var hc = 0; foreach (var s in this) { hc ^= s.GetHashCode(); } return hc; } /// <summary> /// Determines whether this span set is the same as another object. /// </summary> /// <param name="obj">The object to test.</param> /// <returns><c>true</c> if the two objects are equal, otherwise <c>false</c>.</returns> public override bool Equals(object? obj) { var set = obj as NormalizedTextSpanCollection; return this == set; } /// <summary> /// Provides a string representation of the set. /// </summary> /// <returns>The string representation of the set.</returns> public override string ToString() { var value = new StringBuilder("{"); foreach (var s in this) { value.Append(s.ToString()); } value.Append("}"); return value.ToString(); } #endregion // Overridden methods and operators #region Private Helpers private static IList<TextSpan> ListFromSpan(TextSpan span) { IList<TextSpan> list = new List<TextSpan>(1); list.Add(span); return list; } /// <summary> /// Private constructor for use when the span list is already normalized. /// </summary> /// <param name="normalizedSpans">An already normalized span list.</param> private NormalizedTextSpanCollection(OrderedSpanList normalizedSpans) : base(normalizedSpans) { } private static void UpdateSpanUnion(TextSpan span, IList<TextSpan> spans, ref int start, ref int end) { if (end < span.Start) { spans.Add(TextSpan.FromBounds(start, end)); start = -1; end = int.MaxValue; } if (end == int.MaxValue) { start = span.Start; end = span.End; } else { end = Math.Max(end, span.End); } } private static IList<TextSpan> NormalizeSpans(IEnumerable<TextSpan> spans) { if (spans == null) { throw new ArgumentNullException(nameof(spans)); } var sorted = new List<TextSpan>(spans); if (sorted.Count <= 1) { return sorted; } else { sorted.Sort(delegate (TextSpan s1, TextSpan s2) { return s1.Start.CompareTo(s2.Start); }); IList<TextSpan> normalized = new List<TextSpan>(sorted.Count); var oldStart = sorted[0].Start; var oldEnd = sorted[0].End; for (var i = 1; i < sorted.Count; ++i) { var newStart = sorted[i].Start; var newEnd = sorted[i].End; if (oldEnd < newStart) { normalized.Add(TextSpan.FromBounds(oldStart, oldEnd)); oldStart = newStart; oldEnd = newEnd; } else { oldEnd = Math.Max(oldEnd, newEnd); } } normalized.Add(TextSpan.FromBounds(oldStart, oldEnd)); return normalized; } } private class OrderedSpanList : List<TextSpan> { } #endregion // Private Helpers } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Portable/Symbols/AliasSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Symbol representing a using alias appearing in a compilation unit or within a namespace /// declaration. Generally speaking, these symbols do not appear in the set of symbols reachable /// from the unnamed namespace declaration. In other words, when a using alias is used in a /// program, it acts as a transparent alias, and the symbol to which it is an alias is used in /// the symbol table. For example, in the source code /// <pre> /// namespace NS /// { /// using o = System.Object; /// partial class C : o {} /// partial class C : object {} /// partial class C : System.Object {} /// } /// </pre> /// all three declarations for class C are equivalent and result in the same symbol table object /// for C. However, these using alias symbols do appear in the results of certain SemanticModel /// APIs. Specifically, for the base clause of the first of C's class declarations, the /// following APIs may produce a result that contains an AliasSymbol: /// <pre> /// SemanticInfo SemanticModel.GetSemanticInfo(ExpressionSyntax expression); /// SemanticInfo SemanticModel.BindExpression(CSharpSyntaxNode location, ExpressionSyntax expression); /// SemanticInfo SemanticModel.BindType(CSharpSyntaxNode location, ExpressionSyntax type); /// SemanticInfo SemanticModel.BindNamespaceOrType(CSharpSyntaxNode location, ExpressionSyntax type); /// </pre> /// Also, the following are affected if container==null (and, for the latter, when arity==null /// or arity==0): /// <pre> /// IList&lt;string&gt; SemanticModel.LookupNames(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, LookupOptions options = LookupOptions.Default, List&lt;string> result = null); /// IList&lt;Symbol&gt; SemanticModel.LookupSymbols(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, LookupOptions options = LookupOptions.Default, List&lt;Symbol> results = null); /// </pre> /// </summary> internal abstract class AliasSymbol : Symbol { private readonly ImmutableArray<Location> _locations; // NOTE: can be empty for the "global" alias. private readonly string _aliasName; private readonly bool _isExtern; private readonly Symbol? _containingSymbol; protected AliasSymbol(string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern) { Debug.Assert(locations.Length == 1 || (locations.IsEmpty && aliasName == "global")); // It looks like equality implementation depends on this condition. _locations = locations; _aliasName = aliasName; _isExtern = isExtern; _containingSymbol = containingSymbol; } // For the purposes of SemanticModel, it is convenient to have an AliasSymbol for the "global" namespace that "global::" binds // to. This alias symbol is returned only when binding "global::" (special case code). internal static AliasSymbol CreateGlobalNamespaceAlias(NamespaceSymbol globalNamespace) { return new AliasSymbolFromResolvedTarget(globalNamespace, "global", globalNamespace, ImmutableArray<Location>.Empty, isExtern: false); } internal static AliasSymbol CreateCustomDebugInfoAlias(NamespaceOrTypeSymbol targetSymbol, SyntaxToken aliasToken, Symbol? containingSymbol, bool isExtern) { return new AliasSymbolFromResolvedTarget(targetSymbol, aliasToken.ValueText, containingSymbol, ImmutableArray.Create(aliasToken.GetLocation()), isExtern); } internal AliasSymbol ToNewSubmission(CSharpCompilation compilation) { // We can pass basesBeingResolved: null because base type cycles can't cross // submission boundaries - there's no way to depend on a subsequent submission. var previousTarget = Target; if (previousTarget.Kind != SymbolKind.Namespace) { return this; } var expandedGlobalNamespace = compilation.GlobalNamespace; var expandedNamespace = Imports.ExpandPreviousSubmissionNamespace((NamespaceSymbol)previousTarget, expandedGlobalNamespace); return new AliasSymbolFromResolvedTarget(expandedNamespace, Name, ContainingSymbol, _locations, _isExtern); } public sealed override string Name { get { return _aliasName; } } public override SymbolKind Kind { get { return SymbolKind.Alias; } } /// <summary> /// Gets the <see cref="NamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> public abstract NamespaceOrTypeSymbol Target { get; } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return GetDeclaringSyntaxReferenceHelper<UsingDirectiveSyntax>(_locations); } } public sealed override bool IsExtern { get { return _isExtern; } } public override bool IsSealed { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsVirtual { get { return false; } } public override bool IsStatic { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData? ObsoleteAttributeData { get { return null; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <summary> /// Using aliases in C# are always contained within a namespace declaration, or at the top /// level within a compilation unit, within the implicit unnamed namespace declaration. We /// return that as the "containing" symbol, even though the alias isn't a member of the /// namespace as such. /// </summary> public sealed override Symbol? ContainingSymbol { get { return _containingSymbol; } } internal override TResult Accept<TArg, TResult>(CSharpSymbolVisitor<TArg, TResult> visitor, TArg a) { return visitor.VisitAlias(this, a); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitAlias(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitAlias(this); } // basesBeingResolved is only used to break circular references. internal abstract NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved); internal void CheckConstraints(BindingDiagnosticBag diagnostics) { var target = this.Target as TypeSymbol; if ((object?)target != null && Locations.Length > 0) { var corLibrary = this.ContainingAssembly.CorLibrary; var conversions = new TypeConversions(corLibrary); target.CheckAllConstraints(DeclaringCompilation, conversions, Locations[0], diagnostics); } } public override bool Equals(Symbol? obj, TypeCompareKind compareKind) { if (ReferenceEquals(this, obj)) { return true; } if (ReferenceEquals(obj, null)) { return false; } AliasSymbol? other = obj as AliasSymbol; return (object?)other != null && Equals(this.Locations.FirstOrDefault(), other.Locations.FirstOrDefault()) && this.ContainingAssembly.Equals(other.ContainingAssembly, compareKind); } public override int GetHashCode() { if (this.Locations.Length > 0) return this.Locations.First().GetHashCode(); else return Name.GetHashCode(); } internal abstract override bool RequiresCompletion { get; } protected override ISymbol CreateISymbol() { return new PublicModel.AliasSymbol(this); } } internal sealed class AliasSymbolFromSyntax : AliasSymbol { private readonly SyntaxReference _directive; private SymbolCompletionState _state; private NamespaceOrTypeSymbol? _aliasTarget; // lazy binding private BindingDiagnosticBag? _aliasTargetDiagnostics; internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, UsingDirectiveSyntax syntax) : base(syntax.Alias!.Name.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Alias!.Name.Identifier.GetLocation()), isExtern: false) { Debug.Assert(syntax.Alias is object); _directive = syntax.GetReference(); } internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, ExternAliasDirectiveSyntax syntax) : base(syntax.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Identifier.GetLocation()), isExtern: true) { _directive = syntax.GetReference(); } /// <summary> /// Gets the <see cref="NamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> public override NamespaceOrTypeSymbol Target { get { return GetAliasTarget(basesBeingResolved: null); } } // basesBeingResolved is only used to break circular references. internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved) { if (!_state.HasComplete(CompletionPart.AliasTarget)) { // the target is not yet bound. If it is an ordinary alias, bind the target // symbol. If it is an extern alias then find the target in the list of metadata references. var newDiagnostics = BindingDiagnosticBag.GetInstance(); NamespaceOrTypeSymbol symbol = this.IsExtern ? ResolveExternAliasTarget(newDiagnostics) : ResolveAliasTarget(((UsingDirectiveSyntax)_directive.GetSyntax()).Name, newDiagnostics, basesBeingResolved); if ((object?)Interlocked.CompareExchange(ref _aliasTarget, symbol, null) == null) { // Note: It's important that we don't call newDiagnosticsToReadOnlyAndFree here. That call // can force the prompt evaluation of lazy initialized diagnostics. That in turn can // call back into GetAliasTarget on the same thread resulting in a dead lock scenario. bool won = Interlocked.Exchange(ref _aliasTargetDiagnostics, newDiagnostics) == null; Debug.Assert(won, "Only one thread can win the alias target CompareExchange"); _state.NotePartComplete(CompletionPart.AliasTarget); // we do not clear this.aliasTargetName, as another thread might be about to use it for ResolveAliasTarget(...) } else { newDiagnostics.Free(); // Wait for diagnostics to have been reported if another thread resolves the alias _state.SpinWaitComplete(CompletionPart.AliasTarget, default(CancellationToken)); } } return _aliasTarget!; } internal BindingDiagnosticBag AliasTargetDiagnostics { get { GetAliasTarget(null); RoslynDebug.Assert(_aliasTargetDiagnostics != null); return _aliasTargetDiagnostics; } } private NamespaceSymbol ResolveExternAliasTarget(BindingDiagnosticBag diagnostics) { NamespaceSymbol? target; if (!ContainingSymbol!.DeclaringCompilation.GetExternAliasTarget(Name, out target)) { diagnostics.Add(ErrorCode.ERR_BadExternAlias, Locations[0], Name); } RoslynDebug.Assert(target is object); RoslynDebug.Assert(target.IsGlobalNamespace); return target; } private NamespaceOrTypeSymbol ResolveAliasTarget(NameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol>? basesBeingResolved) { var declarationBinder = ContainingSymbol!.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax).WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks); return declarationBinder.BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved).NamespaceOrTypeSymbol; } internal override bool RequiresCompletion { get { return true; } } } internal sealed class AliasSymbolFromResolvedTarget : AliasSymbol { private readonly NamespaceOrTypeSymbol _aliasTarget; internal AliasSymbolFromResolvedTarget(NamespaceOrTypeSymbol target, string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern) : base(aliasName, containingSymbol, locations, isExtern) { _aliasTarget = target; } /// <summary> /// Gets the <see cref="NamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> public override NamespaceOrTypeSymbol Target { get { return _aliasTarget; } } internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved) { return _aliasTarget; } internal override bool RequiresCompletion { get { 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.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Symbol representing a using alias appearing in a compilation unit or within a namespace /// declaration. Generally speaking, these symbols do not appear in the set of symbols reachable /// from the unnamed namespace declaration. In other words, when a using alias is used in a /// program, it acts as a transparent alias, and the symbol to which it is an alias is used in /// the symbol table. For example, in the source code /// <pre> /// namespace NS /// { /// using o = System.Object; /// partial class C : o {} /// partial class C : object {} /// partial class C : System.Object {} /// } /// </pre> /// all three declarations for class C are equivalent and result in the same symbol table object /// for C. However, these using alias symbols do appear in the results of certain SemanticModel /// APIs. Specifically, for the base clause of the first of C's class declarations, the /// following APIs may produce a result that contains an AliasSymbol: /// <pre> /// SemanticInfo SemanticModel.GetSemanticInfo(ExpressionSyntax expression); /// SemanticInfo SemanticModel.BindExpression(CSharpSyntaxNode location, ExpressionSyntax expression); /// SemanticInfo SemanticModel.BindType(CSharpSyntaxNode location, ExpressionSyntax type); /// SemanticInfo SemanticModel.BindNamespaceOrType(CSharpSyntaxNode location, ExpressionSyntax type); /// </pre> /// Also, the following are affected if container==null (and, for the latter, when arity==null /// or arity==0): /// <pre> /// IList&lt;string&gt; SemanticModel.LookupNames(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, LookupOptions options = LookupOptions.Default, List&lt;string> result = null); /// IList&lt;Symbol&gt; SemanticModel.LookupSymbols(CSharpSyntaxNode location, NamespaceOrTypeSymbol container = null, string name = null, int? arity = null, LookupOptions options = LookupOptions.Default, List&lt;Symbol> results = null); /// </pre> /// </summary> internal abstract class AliasSymbol : Symbol { private readonly ImmutableArray<Location> _locations; // NOTE: can be empty for the "global" alias. private readonly string _aliasName; private readonly bool _isExtern; private readonly Symbol? _containingSymbol; protected AliasSymbol(string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern) { Debug.Assert(locations.Length == 1 || (locations.IsEmpty && aliasName == "global")); // It looks like equality implementation depends on this condition. _locations = locations; _aliasName = aliasName; _isExtern = isExtern; _containingSymbol = containingSymbol; } // For the purposes of SemanticModel, it is convenient to have an AliasSymbol for the "global" namespace that "global::" binds // to. This alias symbol is returned only when binding "global::" (special case code). internal static AliasSymbol CreateGlobalNamespaceAlias(NamespaceSymbol globalNamespace) { return new AliasSymbolFromResolvedTarget(globalNamespace, "global", globalNamespace, ImmutableArray<Location>.Empty, isExtern: false); } internal static AliasSymbol CreateCustomDebugInfoAlias(NamespaceOrTypeSymbol targetSymbol, SyntaxToken aliasToken, Symbol? containingSymbol, bool isExtern) { return new AliasSymbolFromResolvedTarget(targetSymbol, aliasToken.ValueText, containingSymbol, ImmutableArray.Create(aliasToken.GetLocation()), isExtern); } internal AliasSymbol ToNewSubmission(CSharpCompilation compilation) { // We can pass basesBeingResolved: null because base type cycles can't cross // submission boundaries - there's no way to depend on a subsequent submission. var previousTarget = Target; if (previousTarget.Kind != SymbolKind.Namespace) { return this; } var expandedGlobalNamespace = compilation.GlobalNamespace; var expandedNamespace = Imports.ExpandPreviousSubmissionNamespace((NamespaceSymbol)previousTarget, expandedGlobalNamespace); return new AliasSymbolFromResolvedTarget(expandedNamespace, Name, ContainingSymbol, _locations, _isExtern); } public sealed override string Name { get { return _aliasName; } } public override SymbolKind Kind { get { return SymbolKind.Alias; } } /// <summary> /// Gets the <see cref="NamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> public abstract NamespaceOrTypeSymbol Target { get; } public override ImmutableArray<Location> Locations { get { return _locations; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return GetDeclaringSyntaxReferenceHelper<UsingDirectiveSyntax>(_locations); } } public sealed override bool IsExtern { get { return _isExtern; } } public override bool IsSealed { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsVirtual { get { return false; } } public override bool IsStatic { get { return false; } } /// <summary> /// Returns data decoded from Obsolete attribute or null if there is no Obsolete attribute. /// This property returns ObsoleteAttributeData.Uninitialized if attribute arguments haven't been decoded yet. /// </summary> internal sealed override ObsoleteAttributeData? ObsoleteAttributeData { get { return null; } } public override Accessibility DeclaredAccessibility { get { return Accessibility.NotApplicable; } } /// <summary> /// Using aliases in C# are always contained within a namespace declaration, or at the top /// level within a compilation unit, within the implicit unnamed namespace declaration. We /// return that as the "containing" symbol, even though the alias isn't a member of the /// namespace as such. /// </summary> public sealed override Symbol? ContainingSymbol { get { return _containingSymbol; } } internal override TResult Accept<TArg, TResult>(CSharpSymbolVisitor<TArg, TResult> visitor, TArg a) { return visitor.VisitAlias(this, a); } public override void Accept(CSharpSymbolVisitor visitor) { visitor.VisitAlias(this); } public override TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor) { return visitor.VisitAlias(this); } // basesBeingResolved is only used to break circular references. internal abstract NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved); internal void CheckConstraints(BindingDiagnosticBag diagnostics) { var target = this.Target as TypeSymbol; if ((object?)target != null && Locations.Length > 0) { var corLibrary = this.ContainingAssembly.CorLibrary; var conversions = new TypeConversions(corLibrary); target.CheckAllConstraints(DeclaringCompilation, conversions, Locations[0], diagnostics); } } public override bool Equals(Symbol? obj, TypeCompareKind compareKind) { if (ReferenceEquals(this, obj)) { return true; } if (ReferenceEquals(obj, null)) { return false; } AliasSymbol? other = obj as AliasSymbol; return (object?)other != null && Equals(this.Locations.FirstOrDefault(), other.Locations.FirstOrDefault()) && this.ContainingAssembly.Equals(other.ContainingAssembly, compareKind); } public override int GetHashCode() { if (this.Locations.Length > 0) return this.Locations.First().GetHashCode(); else return Name.GetHashCode(); } internal abstract override bool RequiresCompletion { get; } protected override ISymbol CreateISymbol() { return new PublicModel.AliasSymbol(this); } } internal sealed class AliasSymbolFromSyntax : AliasSymbol { private readonly SyntaxReference _directive; private SymbolCompletionState _state; private NamespaceOrTypeSymbol? _aliasTarget; // lazy binding private BindingDiagnosticBag? _aliasTargetDiagnostics; internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, UsingDirectiveSyntax syntax) : base(syntax.Alias!.Name.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Alias!.Name.Identifier.GetLocation()), isExtern: false) { Debug.Assert(syntax.Alias is object); _directive = syntax.GetReference(); } internal AliasSymbolFromSyntax(SourceNamespaceSymbol containingSymbol, ExternAliasDirectiveSyntax syntax) : base(syntax.Identifier.ValueText, containingSymbol, ImmutableArray.Create(syntax.Identifier.GetLocation()), isExtern: true) { _directive = syntax.GetReference(); } /// <summary> /// Gets the <see cref="NamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> public override NamespaceOrTypeSymbol Target { get { return GetAliasTarget(basesBeingResolved: null); } } // basesBeingResolved is only used to break circular references. internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved) { if (!_state.HasComplete(CompletionPart.AliasTarget)) { // the target is not yet bound. If it is an ordinary alias, bind the target // symbol. If it is an extern alias then find the target in the list of metadata references. var newDiagnostics = BindingDiagnosticBag.GetInstance(); NamespaceOrTypeSymbol symbol = this.IsExtern ? ResolveExternAliasTarget(newDiagnostics) : ResolveAliasTarget(((UsingDirectiveSyntax)_directive.GetSyntax()).Name, newDiagnostics, basesBeingResolved); if ((object?)Interlocked.CompareExchange(ref _aliasTarget, symbol, null) == null) { // Note: It's important that we don't call newDiagnosticsToReadOnlyAndFree here. That call // can force the prompt evaluation of lazy initialized diagnostics. That in turn can // call back into GetAliasTarget on the same thread resulting in a dead lock scenario. bool won = Interlocked.Exchange(ref _aliasTargetDiagnostics, newDiagnostics) == null; Debug.Assert(won, "Only one thread can win the alias target CompareExchange"); _state.NotePartComplete(CompletionPart.AliasTarget); // we do not clear this.aliasTargetName, as another thread might be about to use it for ResolveAliasTarget(...) } else { newDiagnostics.Free(); // Wait for diagnostics to have been reported if another thread resolves the alias _state.SpinWaitComplete(CompletionPart.AliasTarget, default(CancellationToken)); } } return _aliasTarget!; } internal BindingDiagnosticBag AliasTargetDiagnostics { get { GetAliasTarget(null); RoslynDebug.Assert(_aliasTargetDiagnostics != null); return _aliasTargetDiagnostics; } } private NamespaceSymbol ResolveExternAliasTarget(BindingDiagnosticBag diagnostics) { NamespaceSymbol? target; if (!ContainingSymbol!.DeclaringCompilation.GetExternAliasTarget(Name, out target)) { diagnostics.Add(ErrorCode.ERR_BadExternAlias, Locations[0], Name); } RoslynDebug.Assert(target is object); RoslynDebug.Assert(target.IsGlobalNamespace); return target; } private NamespaceOrTypeSymbol ResolveAliasTarget(NameSyntax syntax, BindingDiagnosticBag diagnostics, ConsList<TypeSymbol>? basesBeingResolved) { var declarationBinder = ContainingSymbol!.DeclaringCompilation.GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax).WithAdditionalFlags(BinderFlags.SuppressConstraintChecks | BinderFlags.SuppressObsoleteChecks); return declarationBinder.BindNamespaceOrTypeSymbol(syntax, diagnostics, basesBeingResolved).NamespaceOrTypeSymbol; } internal override bool RequiresCompletion { get { return true; } } } internal sealed class AliasSymbolFromResolvedTarget : AliasSymbol { private readonly NamespaceOrTypeSymbol _aliasTarget; internal AliasSymbolFromResolvedTarget(NamespaceOrTypeSymbol target, string aliasName, Symbol? containingSymbol, ImmutableArray<Location> locations, bool isExtern) : base(aliasName, containingSymbol, locations, isExtern) { _aliasTarget = target; } /// <summary> /// Gets the <see cref="NamespaceOrTypeSymbol"/> for the /// namespace or type referenced by the alias. /// </summary> public override NamespaceOrTypeSymbol Target { get { return _aliasTarget; } } internal override NamespaceOrTypeSymbol GetAliasTarget(ConsList<TypeSymbol>? basesBeingResolved) { return _aliasTarget; } internal override bool RequiresCompletion { get { return false; } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Portable/DocumentationComments/PEDocumenationCommentUtils.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.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Module PEDocumentationCommentUtils Friend Function GetDocumentationComment( symbol As Symbol, containingPEModule As PEModuleSymbol, preferredCulture As CultureInfo, cancellationToken As CancellationToken, ByRef lazyDocComment As Tuple(Of CultureInfo, String)) As String If lazyDocComment Is Nothing Then Interlocked.CompareExchange(lazyDocComment, Tuple.Create( preferredCulture, containingPEModule.DocumentationProvider.GetDocumentationForSymbol( symbol.GetDocumentationCommentId(), preferredCulture, cancellationToken)), Nothing) End If If Object.Equals(lazyDocComment.Item1, preferredCulture) Then Return lazyDocComment.Item2 End If Return containingPEModule.DocumentationProvider.GetDocumentationForSymbol( symbol.GetDocumentationCommentId(), preferredCulture, cancellationToken) 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.Globalization Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic Friend Module PEDocumentationCommentUtils Friend Function GetDocumentationComment( symbol As Symbol, containingPEModule As PEModuleSymbol, preferredCulture As CultureInfo, cancellationToken As CancellationToken, ByRef lazyDocComment As Tuple(Of CultureInfo, String)) As String If lazyDocComment Is Nothing Then Interlocked.CompareExchange(lazyDocComment, Tuple.Create( preferredCulture, containingPEModule.DocumentationProvider.GetDocumentationForSymbol( symbol.GetDocumentationCommentId(), preferredCulture, cancellationToken)), Nothing) End If If Object.Equals(lazyDocComment.Item1, preferredCulture) Then Return lazyDocComment.Item2 End If Return containingPEModule.DocumentationProvider.GetDocumentationForSymbol( symbol.GetDocumentationCommentId(), preferredCulture, cancellationToken) End Function End Module End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/Core/Portable/Diagnostics/EngineV2/DiagnosticIncrementalAnalyzer.ActiveFileState.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host) /// in memory. /// </summary> private sealed class ActiveFileState { // file state this is for public readonly DocumentId DocumentId; // analysis data for each kind private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty; private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty; public ActiveFileState(DocumentId documentId) => DocumentId = documentId; public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty; public void ResetVersion() { // reset version of cached data so that we can recalculate new data (ex, OnDocumentReset) _syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items); _semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items); } public DocumentAnalysisData GetAnalysisData(AnalysisKind kind) => kind switch { AnalysisKind.Syntax => _syntax, AnalysisKind.Semantic => _semantic, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; public void Save(AnalysisKind kind, DocumentAnalysisData data) { Contract.ThrowIfFalse(data.OldItems.IsDefault); switch (kind) { case AnalysisKind.Syntax: _syntax = data; return; case AnalysisKind.Semantic: _semantic = data; return; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Diagnostics.EngineV2 { internal partial class DiagnosticIncrementalAnalyzer { /// <summary> /// state that is responsible to hold onto local diagnostics data regarding active/opened files (depends on host) /// in memory. /// </summary> private sealed class ActiveFileState { // file state this is for public readonly DocumentId DocumentId; // analysis data for each kind private DocumentAnalysisData _syntax = DocumentAnalysisData.Empty; private DocumentAnalysisData _semantic = DocumentAnalysisData.Empty; public ActiveFileState(DocumentId documentId) => DocumentId = documentId; public bool IsEmpty => _syntax.Items.IsEmpty && _semantic.Items.IsEmpty; public void ResetVersion() { // reset version of cached data so that we can recalculate new data (ex, OnDocumentReset) _syntax = new DocumentAnalysisData(VersionStamp.Default, _syntax.Items); _semantic = new DocumentAnalysisData(VersionStamp.Default, _semantic.Items); } public DocumentAnalysisData GetAnalysisData(AnalysisKind kind) => kind switch { AnalysisKind.Syntax => _syntax, AnalysisKind.Semantic => _semantic, _ => throw ExceptionUtilities.UnexpectedValue(kind) }; public void Save(AnalysisKind kind, DocumentAnalysisData data) { Contract.ThrowIfFalse(data.OldItems.IsDefault); switch (kind) { case AnalysisKind.Syntax: _syntax = data; return; case AnalysisKind.Semantic: _semantic = data; return; default: throw ExceptionUtilities.UnexpectedValue(kind); } } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/MemberInfo/TypeImpl.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.Globalization; using System.Linq; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal class TypeImpl : Type { internal readonly System.Type Type; internal TypeImpl(System.Type type) { Debug.Assert(type != null); this.Type = type; } public static explicit operator TypeImpl(System.Type type) { return type == null ? null : new TypeImpl(type); } public override Assembly Assembly { get { return new AssemblyImpl(this.Type.Assembly); } } public override string AssemblyQualifiedName { get { throw new NotImplementedException(); } } public override Type BaseType { get { return (TypeImpl)this.Type.BaseType; } } public override bool ContainsGenericParameters { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)this.Type.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override string FullName { get { return this.Type.FullName; } } public override Guid GUID { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)this.Type.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override Module Module { get { return new ModuleImpl(this.Type.Module); } } public override string Name { get { return Type.Name; } } public override string Namespace { get { return Type.Namespace; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override Type UnderlyingSystemType { get { return (TypeImpl)Type.UnderlyingSystemType; } } public override bool Equals(Type o) { return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type; } public override bool Equals(object objOther) { return Equals(objOther as Type); } public override int GetHashCode() { return Type.GetHashCode(); } public override int GetArrayRank() { return Type.GetArrayRank(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return Type.GetConstructors((System.Reflection.BindingFlags)bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray(); } public override Type GetElementType() { return (TypeImpl)(Type.GetElementType()); } public override EventInfo GetEvent(string name, BindingFlags flags) { throw new NotImplementedException(); } public override EventInfo[] GetEvents(BindingFlags flags) { throw new NotImplementedException(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { var field = Type.GetField(name, (System.Reflection.BindingFlags)bindingAttr); return (field == null) ? null : new FieldInfoImpl(field); } public override FieldInfo[] GetFields(BindingFlags flags) { return Type.GetFields((System.Reflection.BindingFlags)flags).Select(f => new FieldInfoImpl(f)).ToArray(); } public override Type GetGenericTypeDefinition() { return (TypeImpl)this.Type.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray(); } public override Type GetInterface(string name, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetInterfaces() { return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray(); } public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotImplementedException(); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return Type.GetMember(name, (System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return Type.GetMembers((System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } private static MemberInfo GetMember(System.Reflection.MemberInfo member) { switch (member.MemberType) { case System.Reflection.MemberTypes.Constructor: return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member); case System.Reflection.MemberTypes.Event: return new EventInfoImpl((System.Reflection.EventInfo)member); case System.Reflection.MemberTypes.Field: return new FieldInfoImpl((System.Reflection.FieldInfo)member); case System.Reflection.MemberTypes.Method: return new MethodInfoImpl((System.Reflection.MethodInfo)member); case System.Reflection.MemberTypes.NestedType: return new TypeImpl((System.Reflection.TypeInfo)member); case System.Reflection.MemberTypes.Property: return new PropertyInfoImpl((System.Reflection.PropertyInfo)member); default: throw new NotImplementedException(member.MemberType.ToString()); } } public override MethodInfo[] GetMethods(BindingFlags flags) { return this.Type.GetMethods((System.Reflection.BindingFlags)flags).Select(m => new MethodInfoImpl(m)).ToArray(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotImplementedException(); } public override PropertyInfo[] GetProperties(BindingFlags flags) { throw new NotImplementedException(); } public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotImplementedException(); } public override bool IsAssignableFrom(Type c) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override bool IsEnum { get { return this.Type.IsEnum; } } public override bool IsGenericParameter { get { return Type.IsGenericParameter; } } public override bool IsGenericType { get { return Type.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return Type.IsGenericTypeDefinition; } } public override int GenericParameterPosition { get { return Type.GenericParameterPosition; } } public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations() { var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i)); // A dot is neither necessary nor sufficient for determining whether a member explicitly // implements an interface member, but it does characterize the set of members we're // interested in displaying differently. For example, if the property is from VB, it will // be an explicit interface implementation, but will not have a dot. Therefore, this is // good enough for our mock implementation. var infos = interfaceMaps.SelectMany(map => map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) => implementingMethod.Name.Contains(".") ? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod) : null)); return infos.Where(i => i != null).ToArray(); } private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod) { return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate( new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod)); } public override bool IsInstanceOfType(object o) { throw new NotImplementedException(); } public override bool IsSubclassOf(Type c) { throw new NotImplementedException(); } public override Type MakeArrayType() { return (TypeImpl)this.Type.MakeArrayType(); } public override Type MakeArrayType(int rank) { return (TypeImpl)this.Type.MakeArrayType(rank); } public override Type MakeByRefType() { throw new NotImplementedException(); } public override Type MakeGenericType(params Type[] argTypes) { return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray()); } public override Type MakePointerType() { return (TypeImpl)this.Type.MakePointerType(); } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { System.Reflection.TypeAttributes result = 0; if (this.Type.IsClass) { result |= System.Reflection.TypeAttributes.Class; } if (this.Type.IsInterface) { result |= System.Reflection.TypeAttributes.Interface; } if (this.Type.IsAbstract) { result |= System.Reflection.TypeAttributes.Abstract; } if (this.Type.IsSealed) { result |= System.Reflection.TypeAttributes.Sealed; } return result; } protected override bool IsValueTypeImpl() { return this.Type.IsValueType; } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(binder == null, "NYI"); Debug.Assert(returnType == null, "NYI"); Debug.Assert(types == null, "NYI"); Debug.Assert(modifiers == null, "NYI"); return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0])); } protected override TypeCode GetTypeCodeImpl() { return (TypeCode)System.Type.GetTypeCode(this.Type); } protected override bool HasElementTypeImpl() { return this.Type.HasElementType; } protected override bool IsArrayImpl() { return Type.IsArray; } protected override bool IsByRefImpl() { return Type.IsByRef; } protected override bool IsCOMObjectImpl() { throw new NotImplementedException(); } protected override bool IsContextfulImpl() { throw new NotImplementedException(); } protected override bool IsMarshalByRefImpl() { throw new NotImplementedException(); } protected override bool IsPointerImpl() { return Type.IsPointer; } protected override bool IsPrimitiveImpl() { throw new NotImplementedException(); } public override bool IsAssignableTo(Type c) { throw new NotImplementedException(); } public override string ToString() { return this.Type.ToString(); } public override Type[] GetInterfacesOnType() { var t = this.Type; var builder = ArrayBuilder<Type>.GetInstance(); foreach (var @interface in t.GetInterfaces()) { var map = t.GetInterfaceMap(@interface); if (map.TargetMethods.Any(m => m.DeclaringType == t)) { builder.Add((TypeImpl)@interface); } } return builder.ToArrayAndFree(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Globalization; using System.Linq; using Microsoft.VisualStudio.Debugger.Metadata; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { internal class TypeImpl : Type { internal readonly System.Type Type; internal TypeImpl(System.Type type) { Debug.Assert(type != null); this.Type = type; } public static explicit operator TypeImpl(System.Type type) { return type == null ? null : new TypeImpl(type); } public override Assembly Assembly { get { return new AssemblyImpl(this.Type.Assembly); } } public override string AssemblyQualifiedName { get { throw new NotImplementedException(); } } public override Type BaseType { get { return (TypeImpl)this.Type.BaseType; } } public override bool ContainsGenericParameters { get { throw new NotImplementedException(); } } public override Type DeclaringType { get { return (TypeImpl)this.Type.DeclaringType; } } public override bool IsEquivalentTo(MemberInfo other) { throw new NotImplementedException(); } public override string FullName { get { return this.Type.FullName; } } public override Guid GUID { get { throw new NotImplementedException(); } } public override MemberTypes MemberType { get { return (MemberTypes)this.Type.MemberType; } } public override int MetadataToken { get { throw new NotImplementedException(); } } public override Module Module { get { return new ModuleImpl(this.Type.Module); } } public override string Name { get { return Type.Name; } } public override string Namespace { get { return Type.Namespace; } } public override Type ReflectedType { get { throw new NotImplementedException(); } } public override Type UnderlyingSystemType { get { return (TypeImpl)Type.UnderlyingSystemType; } } public override bool Equals(Type o) { return o != null && o.GetType() == this.GetType() && ((TypeImpl)o).Type == this.Type; } public override bool Equals(object objOther) { return Equals(objOther as Type); } public override int GetHashCode() { return Type.GetHashCode(); } public override int GetArrayRank() { return Type.GetArrayRank(); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return Type.GetConstructors((System.Reflection.BindingFlags)bindingAttr).Select(c => new ConstructorInfoImpl(c)).ToArray(); } public override object[] GetCustomAttributes(bool inherit) { throw new NotImplementedException(); } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override IList<CustomAttributeData> GetCustomAttributesData() { return Type.GetCustomAttributesData().Select(a => new CustomAttributeDataImpl(a)).ToArray(); } public override Type GetElementType() { return (TypeImpl)(Type.GetElementType()); } public override EventInfo GetEvent(string name, BindingFlags flags) { throw new NotImplementedException(); } public override EventInfo[] GetEvents(BindingFlags flags) { throw new NotImplementedException(); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { var field = Type.GetField(name, (System.Reflection.BindingFlags)bindingAttr); return (field == null) ? null : new FieldInfoImpl(field); } public override FieldInfo[] GetFields(BindingFlags flags) { return Type.GetFields((System.Reflection.BindingFlags)flags).Select(f => new FieldInfoImpl(f)).ToArray(); } public override Type GetGenericTypeDefinition() { return (TypeImpl)this.Type.GetGenericTypeDefinition(); } public override Type[] GetGenericArguments() { return Type.GetGenericArguments().Select(t => new TypeImpl(t)).ToArray(); } public override Type GetInterface(string name, bool ignoreCase) { throw new NotImplementedException(); } public override Type[] GetInterfaces() { return Type.GetInterfaces().Select(i => new TypeImpl(i)).ToArray(); } public override System.Reflection.InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotImplementedException(); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return Type.GetMember(name, (System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return Type.GetMembers((System.Reflection.BindingFlags)bindingAttr).Select(GetMember).ToArray(); } private static MemberInfo GetMember(System.Reflection.MemberInfo member) { switch (member.MemberType) { case System.Reflection.MemberTypes.Constructor: return new ConstructorInfoImpl((System.Reflection.ConstructorInfo)member); case System.Reflection.MemberTypes.Event: return new EventInfoImpl((System.Reflection.EventInfo)member); case System.Reflection.MemberTypes.Field: return new FieldInfoImpl((System.Reflection.FieldInfo)member); case System.Reflection.MemberTypes.Method: return new MethodInfoImpl((System.Reflection.MethodInfo)member); case System.Reflection.MemberTypes.NestedType: return new TypeImpl((System.Reflection.TypeInfo)member); case System.Reflection.MemberTypes.Property: return new PropertyInfoImpl((System.Reflection.PropertyInfo)member); default: throw new NotImplementedException(member.MemberType.ToString()); } } public override MethodInfo[] GetMethods(BindingFlags flags) { return this.Type.GetMethods((System.Reflection.BindingFlags)flags).Select(m => new MethodInfoImpl(m)).ToArray(); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { throw new NotImplementedException(); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotImplementedException(); } public override PropertyInfo[] GetProperties(BindingFlags flags) { throw new NotImplementedException(); } public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, CultureInfo culture, string[] namedParameters) { throw new NotImplementedException(); } public override bool IsAssignableFrom(Type c) { throw new NotImplementedException(); } public override bool IsDefined(Type attributeType, bool inherit) { throw new NotImplementedException(); } public override bool IsEnum { get { return this.Type.IsEnum; } } public override bool IsGenericParameter { get { return Type.IsGenericParameter; } } public override bool IsGenericType { get { return Type.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return Type.IsGenericTypeDefinition; } } public override int GenericParameterPosition { get { return Type.GenericParameterPosition; } } public override ExplicitInterfaceInfo[] GetExplicitInterfaceImplementations() { var interfaceMaps = Type.GetInterfaces().Select(i => Type.GetInterfaceMap(i)); // A dot is neither necessary nor sufficient for determining whether a member explicitly // implements an interface member, but it does characterize the set of members we're // interested in displaying differently. For example, if the property is from VB, it will // be an explicit interface implementation, but will not have a dot. Therefore, this is // good enough for our mock implementation. var infos = interfaceMaps.SelectMany(map => map.InterfaceMethods.Zip(map.TargetMethods, (interfaceMethod, implementingMethod) => implementingMethod.Name.Contains(".") ? MakeExplicitInterfaceInfo(interfaceMethod, implementingMethod) : null)); return infos.Where(i => i != null).ToArray(); } private static ExplicitInterfaceInfo MakeExplicitInterfaceInfo(System.Reflection.MethodInfo interfaceMethod, System.Reflection.MethodInfo implementingMethod) { return (ExplicitInterfaceInfo)typeof(ExplicitInterfaceInfo).Instantiate( new MethodInfoImpl(interfaceMethod), new MethodInfoImpl(implementingMethod)); } public override bool IsInstanceOfType(object o) { throw new NotImplementedException(); } public override bool IsSubclassOf(Type c) { throw new NotImplementedException(); } public override Type MakeArrayType() { return (TypeImpl)this.Type.MakeArrayType(); } public override Type MakeArrayType(int rank) { return (TypeImpl)this.Type.MakeArrayType(rank); } public override Type MakeByRefType() { throw new NotImplementedException(); } public override Type MakeGenericType(params Type[] argTypes) { return (TypeImpl)this.Type.MakeGenericType(argTypes.Select(t => ((TypeImpl)t).Type).ToArray()); } public override Type MakePointerType() { return (TypeImpl)this.Type.MakePointerType(); } protected override System.Reflection.TypeAttributes GetAttributeFlagsImpl() { System.Reflection.TypeAttributes result = 0; if (this.Type.IsClass) { result |= System.Reflection.TypeAttributes.Class; } if (this.Type.IsInterface) { result |= System.Reflection.TypeAttributes.Interface; } if (this.Type.IsAbstract) { result |= System.Reflection.TypeAttributes.Abstract; } if (this.Type.IsSealed) { result |= System.Reflection.TypeAttributes.Sealed; } return result; } protected override bool IsValueTypeImpl() { return this.Type.IsValueType; } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, System.Reflection.CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { Debug.Assert(binder == null, "NYI"); Debug.Assert(returnType == null, "NYI"); Debug.Assert(types == null, "NYI"); Debug.Assert(modifiers == null, "NYI"); return new PropertyInfoImpl(Type.GetProperty(name, (System.Reflection.BindingFlags)bindingAttr, binder: null, returnType: null, types: new System.Type[0], modifiers: new System.Reflection.ParameterModifier[0])); } protected override TypeCode GetTypeCodeImpl() { return (TypeCode)System.Type.GetTypeCode(this.Type); } protected override bool HasElementTypeImpl() { return this.Type.HasElementType; } protected override bool IsArrayImpl() { return Type.IsArray; } protected override bool IsByRefImpl() { return Type.IsByRef; } protected override bool IsCOMObjectImpl() { throw new NotImplementedException(); } protected override bool IsContextfulImpl() { throw new NotImplementedException(); } protected override bool IsMarshalByRefImpl() { throw new NotImplementedException(); } protected override bool IsPointerImpl() { return Type.IsPointer; } protected override bool IsPrimitiveImpl() { throw new NotImplementedException(); } public override bool IsAssignableTo(Type c) { throw new NotImplementedException(); } public override string ToString() { return this.Type.ToString(); } public override Type[] GetInterfacesOnType() { var t = this.Type; var builder = ArrayBuilder<Type>.GetInstance(); foreach (var @interface in t.GetInterfaces()) { var map = t.GetInterfaceMap(@interface); if (map.TargetMethods.Any(m => m.DeclaringType == t)) { builder.Add((TypeImpl)@interface); } } return builder.ToArrayAndFree(); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Tools/BuildValidator/xlf/BuildValidatorResources.de.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../BuildValidatorResources.resx"> <body> <trans-unit id="Assemblies_to_be_excluded_substring_match"> <source>Assemblies to be excluded (substring match)</source> <target state="translated">Auszuschließende Assemblys (Übereinstimmung mit Teilzeichenfolge)</target> <note /> </trans-unit> <trans-unit id="Do_not_output_log_information_to_console"> <source>Do not output log information to console</source> <target state="translated">Protokollinformationen nicht in Konsole ausgeben</target> <note /> </trans-unit> <trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original"> <source>Output debug info when rebuild is not equal to the original</source> <target state="translated">Debuginformationen ausgeben, wenn die Neuerstellung nicht dem Original entspricht</target> <note /> </trans-unit> <trans-unit id="Output_verbose_log_information"> <source>Output verbose log information</source> <target state="translated">Ausführliche Protokollinformationen ausgeben</target> <note /> </trans-unit> <trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times"> <source>Path to assemblies to rebuild (can be specified one or more times)</source> <target state="translated">Pfad zu den neu zu erstellenden Assemblys (kann mindestens einmal angegeben werden).</target> <note /> </trans-unit> <trans-unit id="Path_to_output_debug_info"> <source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source> <target state="translated">Pfad zu ausgegebenen Debuginformationen. Standardmäßig wird das Temp-Verzeichnis des Benutzers verwendet. Beachten Sie, dass ein eindeutiger Debugpfad für jede Instanz des Tools angegeben werden muss, die mit aktiviertem "--debug" ausgeführt wird.</target> <note /> </trans-unit> <trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times"> <source>Path to referenced assemblies (can be specified zero or more times)</source> <target state="translated">Pfad zu referenzierten Assemblys (kann mindestens einmal oder gar nicht angegeben werden)</target> <note /> </trans-unit> <trans-unit id="Path_to_sources_to_use_in_rebuild"> <source>Path to sources to use in rebuild</source> <target state="translated">Pfad zu Quellen, die bei der Neuerstellung verwendet werden sollen</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="de" original="../BuildValidatorResources.resx"> <body> <trans-unit id="Assemblies_to_be_excluded_substring_match"> <source>Assemblies to be excluded (substring match)</source> <target state="translated">Auszuschließende Assemblys (Übereinstimmung mit Teilzeichenfolge)</target> <note /> </trans-unit> <trans-unit id="Do_not_output_log_information_to_console"> <source>Do not output log information to console</source> <target state="translated">Protokollinformationen nicht in Konsole ausgeben</target> <note /> </trans-unit> <trans-unit id="Output_debug_info_when_rebuild_is_not_equal_to_the_original"> <source>Output debug info when rebuild is not equal to the original</source> <target state="translated">Debuginformationen ausgeben, wenn die Neuerstellung nicht dem Original entspricht</target> <note /> </trans-unit> <trans-unit id="Output_verbose_log_information"> <source>Output verbose log information</source> <target state="translated">Ausführliche Protokollinformationen ausgeben</target> <note /> </trans-unit> <trans-unit id="Path_to_assemblies_to_rebuild_can_be_specified_one_or_more_times"> <source>Path to assemblies to rebuild (can be specified one or more times)</source> <target state="translated">Pfad zu den neu zu erstellenden Assemblys (kann mindestens einmal angegeben werden).</target> <note /> </trans-unit> <trans-unit id="Path_to_output_debug_info"> <source>Path to output debug info. Defaults to the user temp directory. Note that a unique debug path should be specified for every instance of the tool running with `--debug` enabled.</source> <target state="translated">Pfad zu ausgegebenen Debuginformationen. Standardmäßig wird das Temp-Verzeichnis des Benutzers verwendet. Beachten Sie, dass ein eindeutiger Debugpfad für jede Instanz des Tools angegeben werden muss, die mit aktiviertem "--debug" ausgeführt wird.</target> <note /> </trans-unit> <trans-unit id="Path_to_referenced_assemblies_can_be_specified_zero_or_more_times"> <source>Path to referenced assemblies (can be specified zero or more times)</source> <target state="translated">Pfad zu referenzierten Assemblys (kann mindestens einmal oder gar nicht angegeben werden)</target> <note /> </trans-unit> <trans-unit id="Path_to_sources_to_use_in_rebuild"> <source>Path to sources to use in rebuild</source> <target state="translated">Pfad zu Quellen, die bei der Neuerstellung verwendet werden sollen</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/ByteKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ByteKeywordRecommender() : base(SyntaxKind.ByteKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Byte; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class ByteKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public ByteKeywordRecommender() : base(SyntaxKind.ByteKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsEnumBaseListContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Byte; } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/Core/Portable/Structure/Syntax/AbstractSyntaxStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.Structure { internal abstract class AbstractSyntaxStructureProvider { public abstract void CollectBlockSpans( SyntaxToken previousToken, SyntaxNode node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken); public abstract void CollectBlockSpans( SyntaxTrivia trivia, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.Structure { internal abstract class AbstractSyntaxStructureProvider { public abstract void CollectBlockSpans( SyntaxToken previousToken, SyntaxNode node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken); public abstract void CollectBlockSpans( SyntaxTrivia trivia, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/VisualBasicTest/KeywordHighlighting/MultiLineIfBlockHighlighterTests.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.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class MultiLineIfBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(MultiLineIfBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() {|Cursor:[|If|]|} a < b [|Then|] a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b {|Cursor:[|Then|]|} a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf3() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b [|Then|] a = b {|Cursor:[|ElseIf|]|} DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf4() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b [|Then|] a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|{|Cursor:Else|}|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf5() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b [|Then|] a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a {|Cursor:[|End If|]|} End Sub End Class]]></Text>) End Function <WorkItem(542614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542614")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf6() As Task Await TestAsync(<Text><![CDATA[ Imports System Module M Sub C() Dim x As Integer = 5 [|If|] x < 0 [|Then|] {|Cursor:[|Else If|]|} [|End If|] End Sub End Module]]></Text>) 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.VisualBasic.KeywordHighlighting Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.KeywordHighlighting Public Class MultiLineIfBlockHighlighterTests Inherits AbstractVisualBasicKeywordHighlighterTests Friend Overrides Function GetHighlighterType() As Type Return GetType(MultiLineIfBlockHighlighter) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf1() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() {|Cursor:[|If|]|} a < b [|Then|] a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf2() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b {|Cursor:[|Then|]|} a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf3() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b [|Then|] a = b {|Cursor:[|ElseIf|]|} DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf4() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b [|Then|] a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|{|Cursor:Else|}|] If a < b Then a = b Else b = a [|End If|] End Sub End Class]]></Text>) End Function <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf5() As Task Await TestAsync(<Text><![CDATA[ Class C Sub M() [|If|] a < b [|Then|] a = b [|ElseIf|] DateTime.Now.Ticks Mod 2 = 0 Throw New RandomException [|Else|] If a < b Then a = b Else b = a {|Cursor:[|End If|]|} End Sub End Class]]></Text>) End Function <WorkItem(542614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542614")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)> Public Async Function TestMultilineIf6() As Task Await TestAsync(<Text><![CDATA[ Imports System Module M Sub C() Dim x As Integer = 5 [|If|] x < 0 [|Then|] {|Cursor:[|Else If|]|} [|End If|] End Sub End Module]]></Text>) End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Test2/IntelliSense/CSharpCompletionCommandHandlerTests_DateAndTime.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.Globalization Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_DateAndTime <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFirstQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingEndingQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(" $$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFormattingComponentColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}"";", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingColonWithinFormattingComponent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(":ff$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString("":FF"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("f$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableDateTimeCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime? d) { d?.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $@"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Globalization Namespace Microsoft.CodeAnalysis.Editor.UnitTests.IntelliSense <[UseExportProvider]> Public Class CSharpCompletionCommandHandlerTests_DateAndTime <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFirstQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString($$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G)", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingEndingQuote(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(" $$); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("""") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsShownWithDefaultFormatStringAfterTypingFormattingComponentColon(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}"";", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function CompletionListIsNotShownAfterTypingColonWithinFormattingComponent(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars(":") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString(""G"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString(":ff$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("d.ToString("":FF"")", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("f$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { d.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestNullableDateTimeCompletion(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime? d) { d?.ToString("hh:mm:$$"); } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("G", inlineDescription:=FeaturesResources.general_long_date_time) state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:G}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = $""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function ExplicitInvoke_OverwriteExisting_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:ff$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() Await state.AssertSelectedCompletionItem("ff") state.SendDownKey() Await state.AssertSelectedCompletionItem("FF") state.SendTab() Await state.AssertNoCompletionSession() Assert.Contains("_ = @$""Text {d:FF}""", state.GetLineTextFromCaretPosition(), StringComparison.Ordinal) End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_BeginningOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $@"Text {d:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertCompletionSession() Await state.AssertSelectedCompletionItem("f") End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TestExample1_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {d:hh:mm:$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendInvokeCompletionList() state.SendTypeChars("ss") Await state.AssertSelectedCompletionItem("ss", inlineDescription:=FeaturesResources.second_2_digits) Dim description = Await state.GetSelectedItemDescriptionAsync() Dim text = description.Text If CultureInfo.CurrentCulture.Name <> "en-US" Then Assert.Contains($"hh:mm:ss (en-US) → 01:45:30", text) Assert.Contains($"hh:mm:ss ({CultureInfo.CurrentCulture.Name}) → 01:45:30", text) Else Assert.Contains("hh:mm:ss → 01:45:30", text) End If End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation1(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = $"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function <WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Completion)> Public Async Function TypeChar_MiddleOfWord_StringInterpolation2(showCompletionInArgumentLists As Boolean) As Task Using state = TestStateFactory.CreateCSharpTestState( <Document><![CDATA[ using System; class c { void goo(DateTime d) { _ = @$"Text {date:f$$}"; } } ]]></Document>, showCompletionInArgumentLists:=showCompletionInArgumentLists) state.SendTypeChars("f") Await state.AssertNoCompletionSession() End Using End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/VisualBasic/Portable/EditAndContinue/SyntaxComparer.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue Friend NotInheritable Class SyntaxComparer Inherits AbstractSyntaxComparer Friend Shared ReadOnly TopLevel As SyntaxComparer = New SyntaxComparer(Nothing, Nothing, Nothing, Nothing, compareStatementSyntax:=False) Friend Shared ReadOnly Statement As SyntaxComparer = New SyntaxComparer(Nothing, Nothing, Nothing, Nothing, compareStatementSyntax:=True) Private ReadOnly _matchingLambdas As Boolean Public Sub New(oldRoot As SyntaxNode, newRoot As SyntaxNode, oldRootChildren As IEnumerable(Of SyntaxNode), newRootChildren As IEnumerable(Of SyntaxNode), Optional matchingLambdas As Boolean = False, Optional compareStatementSyntax As Boolean = False) MyBase.New(oldRoot, newRoot, oldRootChildren, newRootChildren, compareStatementSyntax) _matchingLambdas = matchingLambdas End Sub Protected Overrides Function IsLambdaBodyStatementOrExpression(node As SyntaxNode) As Boolean Return LambdaUtilities.IsLambdaBodyStatementOrExpression(node) End Function #Region "Labels" ' Assumptions: ' - Each listed label corresponds to one or more syntax kinds. ' - Nodes with same labels might produce Update edits, nodes with different labels don't. ' - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label. ' (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label). ' - All descendants of a node whose kind is listed here will be ignored regardless of their labels Friend Enum Label ' ' Top Syntax ' CompilationUnit [Option] ' tied to parent Import ' tied to parent Attributes ' tied to parent NamespaceDeclaration TypeDeclaration EnumDeclaration DelegateDeclaration FieldDeclaration ' tied to parent FieldVariableDeclarator ' tied to parent PInvokeDeclaration ' tied to parent MethodDeclaration ' tied to parent ConstructorDeclaration ' tied to parent OperatorDeclaration ' tied to parent PropertyDeclaration ' tied to parent CustomEventDeclaration ' tied to parent EnumMemberDeclaration ' tied to parent AccessorDeclaration ' tied to parent ' Opening statement of a type, method, operator, constructor, property, and accessor. ' We need to represent this node in the graph since attributes, (generic) parameters are its children. ' However, we don't need to have a specialized label for each type of declaration statement since ' they are tied to the parent and each parent has a single declaration statement. DeclarationStatement ' tied to parent ' Event statement is either a child of a custom event or a stand-alone event field declaration. EventStatement ' tied to parent TypeParameterList ' tied to parent TypeParameter ' tied to parent ParameterList ' tied to parent Parameter ' tied to parent FieldOrParameterName ' tied to grand-grandparent (type or method declaration) AttributeList ' tied to parent Attribute ' tied to parent ' ' Statement Syntax ' BodyBlock ' We need to represent sub/function/ctor/accessor/operator declaration ' begin And End statements since they may be active statements. BodyBegin ' tied to parent LambdaRoot TryBlock TryStatement ' tied to parent CatchBlock ' tied to parent CatchStatement ' tied to parent FinallyBlock ' tied to parent FinallyStatement ' tied to parent CatchFilterClause ' tied to parent EndTryStatement ' tied to parent ForBlock ForEachBlock ForEachStatement ' tied to parent ForStatement ' tied to parent ForStepClause ' tied to parent NextStatement ' tied to parent UsingBlock UsingStatement ' tied to parent EndUsingStatement ' tied to parent SyncLockBlock SyncLockStatement ' tied to parent EndSyncLockStatement ' tied to parent WithBlock WithStatement ' tied to parent EndWithStatement ' tied to parent DoWhileBlock DoWhileStatement ' tied to parent EndLoop ' tied to parent WhileOrUntilClause ' tied to parent IfBlock IfStatement ' tied to parent ElseIfBlock ' tied to parent ElseIfStatement ' tied to parent ElseBlock ' tied to parent ElseStatement ' tied to parent EndIfStatement ' tied to parent SelectBlock SelectStatement ' tied to parent CaseBlock ' tied to parent CaseStatement ' tied to parent CaseClause ' tied to parent EndSelectStatement ' tied to parent ReDimStatement ReDimClause ' tied to parent ' Exit Sub|Function|Operator|Property|For|While|Do|Select|Try ExitStatement ' Continue While|Do|For ContinueStatement ' Throw, Throw expr ThrowStatement ErrorStatement ' Return, Return expr ReturnStatement OnErrorStatement ResumeStatement ' GoTo, Stop, End GoToStatement LabelStatement EraseStatement ExpressionStatement AssignmentStatement EventHandlerStatement YieldStatement LocalDeclarationStatement ' tied to parent LocalVariableDeclarator ' tied to parent ' TODO: AwaitExpression Lambda LambdaBodyBegin ' tied to parent QueryExpression AggregateClause ' tied to parent JoinClause ' tied to parent FromClause ' tied to parent WhereClauseLambda ' tied to parent LetClause ' tied to parent SelectClauseLambda ' tied to parent PartitionWhileLambda ' tied to parent PartitionClause ' tied to parent GroupByClause ' tied to parent OrderByClause ' tied to parent CollectionRangeVariable ' tied to parent (FromClause, JoinClause, AggregateClause) ExpressionRangeVariable ' tied to parent (LetClause, SelectClause, GroupByClause keys) ExpressionRangeVariableItems ' tied to parent (GroupByClause items) FunctionAggregationLambda ' tied to parent (JoinClause, GroupByClause, AggregateClause) OrderingLambda ' tied to parent (OrderByClause) JoinConditionLambda ' tied to parent (JoinClause) LocalVariableName ' tied to parent BodyEnd ' tied to parent ' helpers Count Ignored = IgnoredNode End Enum ''' <summary> ''' Return true if it is desirable to report two edits (delete and insert) rather than a move edit ''' when the node changes its parent. ''' </summary> Private Overloads Shared Function TiedToAncestor(label As Label) As Integer Select Case label ' Top level syntax Case Label.Option, Label.Import, Label.Attributes, Label.FieldDeclaration, Label.FieldVariableDeclarator, Label.PInvokeDeclaration, Label.MethodDeclaration, Label.OperatorDeclaration, Label.ConstructorDeclaration, Label.PropertyDeclaration, Label.CustomEventDeclaration, Label.EnumMemberDeclaration, Label.AccessorDeclaration, Label.DeclarationStatement, Label.EventStatement, Label.TypeParameterList, Label.TypeParameter, Label.ParameterList, Label.Parameter, Label.AttributeList, Label.Attribute Return 1 Case Label.FieldOrParameterName Return 3 ' type or method declaration ' Statement syntax Case Label.BodyBegin, Label.LambdaBodyBegin, Label.BodyEnd, Label.TryStatement, Label.CatchBlock, Label.CatchStatement, Label.FinallyBlock, Label.FinallyStatement, Label.CatchFilterClause, Label.EndTryStatement, Label.ForEachStatement, Label.ForStatement, Label.ForStepClause, Label.NextStatement, Label.UsingStatement, Label.EndUsingStatement, Label.SyncLockStatement, Label.EndSyncLockStatement, Label.WithStatement, Label.EndWithStatement, Label.DoWhileStatement, Label.WhileOrUntilClause, Label.EndLoop, Label.IfStatement, Label.ElseIfBlock, Label.ElseIfStatement, Label.ElseBlock, Label.ElseStatement, Label.EndIfStatement, Label.SelectStatement, Label.CaseBlock, Label.CaseStatement, Label.CaseClause, Label.EndSelectStatement, Label.ReDimClause, Label.AggregateClause, Label.JoinClause, Label.FromClause, Label.WhereClauseLambda, Label.LetClause, Label.SelectClauseLambda, Label.PartitionWhileLambda, Label.PartitionClause, Label.GroupByClause, Label.OrderByClause, Label.CollectionRangeVariable, Label.ExpressionRangeVariable, Label.ExpressionRangeVariableItems, Label.FunctionAggregationLambda, Label.OrderingLambda, Label.JoinConditionLambda, Label.LocalDeclarationStatement, Label.LocalVariableDeclarator, Label.LocalVariableName Return 1 Case Else Return 0 End Select Throw New NotImplementedException() End Function Friend Overrides Function Classify(kind As Integer, node As SyntaxNode, ByRef isLeaf As Boolean) As Integer Return Classify(CType(kind, SyntaxKind), node, isLeaf, ignoreVariableDeclarations:=False) End Function ' internal for testing Friend Overloads Function Classify(kind As SyntaxKind, nodeOpt As SyntaxNode, ByRef isLeaf As Boolean, ignoreVariableDeclarations As Boolean) As Label If _compareStatementSyntax Then Return ClassifyStatementSyntax(kind, nodeOpt, isLeaf) End If Return ClassifyTopSytnax(kind, nodeOpt, isLeaf, ignoreVariableDeclarations) End Function Friend Shared Function ClassifyStatementSyntax(kind As SyntaxKind, nodeOpt As SyntaxNode, ByRef isLeaf As Boolean) As Label isLeaf = False Select Case kind Case SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return Label.BodyBlock Case SyntaxKind.SubStatement, SyntaxKind.SubNewStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement isLeaf = True Return Label.BodyBegin Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader ' Header is a leaf so that we don't descent into lambda parameters. isLeaf = True Return Label.LambdaBodyBegin Case SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement, SyntaxKind.EndOperatorStatement, SyntaxKind.EndGetStatement, SyntaxKind.EndSetStatement, SyntaxKind.EndAddHandlerStatement, SyntaxKind.EndRemoveHandlerStatement, SyntaxKind.EndRaiseEventStatement isLeaf = True Return Label.BodyEnd Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock, SyntaxKind.WhileBlock Return Label.DoWhileBlock Case SyntaxKind.SimpleDoStatement, SyntaxKind.DoWhileStatement, SyntaxKind.DoUntilStatement, SyntaxKind.WhileStatement Return Label.DoWhileStatement Case SyntaxKind.WhileClause, SyntaxKind.UntilClause Return Label.WhileOrUntilClause Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement, SyntaxKind.EndWhileStatement Return Label.EndLoop Case SyntaxKind.ForBlock Return Label.ForBlock Case SyntaxKind.ForEachBlock Return Label.ForEachBlock Case SyntaxKind.ForStatement Return Label.ForStatement Case SyntaxKind.ForEachStatement Return Label.ForEachStatement Case SyntaxKind.ForStepClause Return Label.ForStepClause Case SyntaxKind.NextStatement isLeaf = True Return Label.NextStatement Case SyntaxKind.UsingBlock Return Label.UsingBlock Case SyntaxKind.UsingStatement Return Label.UsingStatement Case SyntaxKind.EndUsingStatement isLeaf = True Return Label.EndUsingStatement Case SyntaxKind.SyncLockBlock Return Label.SyncLockBlock Case SyntaxKind.SyncLockStatement Return Label.SyncLockStatement Case SyntaxKind.EndSyncLockStatement isLeaf = True Return Label.EndSyncLockStatement Case SyntaxKind.WithBlock Return Label.WithBlock Case SyntaxKind.WithStatement Return Label.WithStatement Case SyntaxKind.EndWithStatement isLeaf = True Return Label.EndWithStatement Case SyntaxKind.LocalDeclarationStatement Return Label.LocalDeclarationStatement Case SyntaxKind.VariableDeclarator Return Label.LocalVariableDeclarator Case SyntaxKind.ModifiedIdentifier Return Label.LocalVariableName Case SyntaxKind.MultiLineIfBlock, SyntaxKind.SingleLineIfStatement Return Label.IfBlock Case SyntaxKind.MultiLineIfBlock, SyntaxKind.SingleLineIfStatement Return Label.IfBlock Case SyntaxKind.IfStatement Return Label.IfStatement Case SyntaxKind.ElseIfBlock Return Label.ElseIfBlock Case SyntaxKind.ElseIfStatement Return Label.ElseIfStatement Case SyntaxKind.ElseBlock, SyntaxKind.SingleLineElseClause Return Label.ElseBlock Case SyntaxKind.ElseStatement isLeaf = True Return Label.ElseStatement Case SyntaxKind.EndIfStatement isLeaf = True Return Label.EndIfStatement Case SyntaxKind.TryBlock Return Label.TryBlock Case SyntaxKind.TryBlock Return Label.TryBlock Case SyntaxKind.TryStatement Return Label.TryStatement Case SyntaxKind.CatchBlock Return Label.CatchBlock Case SyntaxKind.CatchStatement Return Label.CatchStatement Case SyntaxKind.FinallyBlock Return Label.FinallyBlock Case SyntaxKind.FinallyStatement Return Label.FinallyStatement Case SyntaxKind.CatchFilterClause Return Label.CatchFilterClause Case SyntaxKind.EndTryStatement isLeaf = True Return Label.EndTryStatement Case SyntaxKind.ErrorStatement isLeaf = True Return Label.ErrorStatement Case SyntaxKind.ThrowStatement Return Label.ThrowStatement Case SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToLabelStatement, SyntaxKind.OnErrorResumeNextStatement Return Label.OnErrorStatement Case SyntaxKind.ResumeStatement, SyntaxKind.ResumeLabelStatement, SyntaxKind.ResumeNextStatement Return Label.ResumeStatement Case SyntaxKind.SelectBlock Return Label.SelectBlock Case SyntaxKind.SelectStatement Return Label.SelectStatement Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock Return Label.CaseBlock Case SyntaxKind.CaseStatement, SyntaxKind.CaseElseStatement Return Label.CaseStatement Case SyntaxKind.ElseCaseClause, SyntaxKind.SimpleCaseClause, SyntaxKind.RangeCaseClause, SyntaxKind.CaseEqualsClause, SyntaxKind.CaseNotEqualsClause, SyntaxKind.CaseLessThanClause, SyntaxKind.CaseLessThanOrEqualClause, SyntaxKind.CaseGreaterThanOrEqualClause, SyntaxKind.CaseGreaterThanClause Return Label.CaseClause Case SyntaxKind.EndSelectStatement isLeaf = True Return Label.EndSelectStatement Case SyntaxKind.ExitForStatement, SyntaxKind.ExitDoStatement, SyntaxKind.ExitWhileStatement, SyntaxKind.ExitSelectStatement, SyntaxKind.ExitTryStatement, SyntaxKind.ExitSubStatement, SyntaxKind.ExitFunctionStatement, SyntaxKind.ExitOperatorStatement, SyntaxKind.ExitPropertyStatement isLeaf = True Return Label.ExitStatement Case SyntaxKind.ContinueWhileStatement, SyntaxKind.ContinueDoStatement, SyntaxKind.ContinueForStatement isLeaf = True Return Label.ContinueStatement Case SyntaxKind.ReturnStatement Return Label.ReturnStatement Case SyntaxKind.GoToStatement, SyntaxKind.StopStatement, SyntaxKind.EndStatement isLeaf = True Return Label.GoToStatement Case SyntaxKind.LabelStatement isLeaf = True Return Label.LabelStatement Case SyntaxKind.EraseStatement isLeaf = True Return Label.EraseStatement Case SyntaxKind.ExpressionStatement, SyntaxKind.CallStatement Return Label.ExpressionStatement Case SyntaxKind.MidAssignmentStatement, SyntaxKind.SimpleAssignmentStatement, SyntaxKind.AddAssignmentStatement, SyntaxKind.SubtractAssignmentStatement, SyntaxKind.MultiplyAssignmentStatement, SyntaxKind.DivideAssignmentStatement, SyntaxKind.IntegerDivideAssignmentStatement, SyntaxKind.ExponentiateAssignmentStatement, SyntaxKind.LeftShiftAssignmentStatement, SyntaxKind.RightShiftAssignmentStatement, SyntaxKind.ConcatenateAssignmentStatement Return Label.AssignmentStatement Case SyntaxKind.AddHandlerStatement, SyntaxKind.RemoveHandlerStatement, SyntaxKind.RaiseEventStatement Return Label.EventHandlerStatement Case SyntaxKind.ReDimStatement, SyntaxKind.ReDimPreserveStatement Return Label.ReDimStatement Case SyntaxKind.RedimClause Return Label.ReDimClause Case SyntaxKind.YieldStatement Return Label.YieldStatement Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return Label.Lambda Case SyntaxKind.FunctionLambdaHeader, SyntaxKind.SubLambdaHeader ' TODO: Parameters are not mapped? isLeaf = True Return Label.Ignored Case SyntaxKind.QueryExpression Return Label.QueryExpression Case SyntaxKind.WhereClause Return Label.WhereClauseLambda Case SyntaxKind.LetClause Return Label.LetClause Case SyntaxKind.SkipClause, SyntaxKind.TakeClause Return Label.PartitionClause Case SyntaxKind.TakeWhileClause, SyntaxKind.SkipWhileClause Return Label.PartitionWhileLambda Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Return Label.OrderingLambda Case SyntaxKind.FunctionAggregation Return Label.FunctionAggregationLambda Case SyntaxKind.SelectClause Return Label.SelectClauseLambda Case SyntaxKind.GroupByClause Return Label.GroupByClause Case SyntaxKind.OrderByClause Return Label.OrderByClause Case SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause Return Label.JoinClause Case SyntaxKind.AggregateClause Return Label.AggregateClause Case SyntaxKind.FromClause Return Label.FromClause Case SyntaxKind.ExpressionRangeVariable ' Select, Let, GroupBy ' ' All ERVs need to be included in the map, ' so that we are able to map range variable declarations. ' ' Since we don't distinguish between ERVs that represent a lambda and non-lambda ERVs, ' we need to be handle cases when one maps to the other (and vice versa). ' This is handled in GetCorresondingLambdaBody. ' ' On the other hand we don't want map across lambda body boundaries. ' Hence we use a label for ERVs in Items distinct from one for Keys of a GroupBy clause. ' ' Node that the nodeOpt is Nothing only when comparing nodes for value equality. ' In that case it doesn't matter what label the node has as long as it has some. If nodeOpt IsNot Nothing AndAlso nodeOpt.Parent.IsKind(SyntaxKind.GroupByClause) AndAlso nodeOpt.SpanStart < DirectCast(nodeOpt.Parent, GroupByClauseSyntax).ByKeyword.SpanStart Then Return Label.ExpressionRangeVariableItems Else Return Label.ExpressionRangeVariable End If Case SyntaxKind.CollectionRangeVariable ' From, Aggregate ' ' All CRVs need to be included in the map, ' so that we are able to map range variable declarations. Return Label.CollectionRangeVariable Case SyntaxKind.JoinCondition ' TODO: Return Label.JoinConditionLambda ' TODO: 'Case SyntaxKind.AwaitExpression ' Return Label.AwaitExpression Case SyntaxKind.GenericName ' optimization - no need to dig into type instantiations isLeaf = True Return Label.Ignored Case Else Return Label.Ignored End Select End Function Private Shared Function ClassifyTopSytnax(kind As SyntaxKind, nodeOpt As SyntaxNode, ByRef isLeaf As Boolean, ignoreVariableDeclarations As Boolean) As Label Select Case kind Case SyntaxKind.CompilationUnit isLeaf = False Return Label.CompilationUnit Case SyntaxKind.OptionStatement isLeaf = True Return Label.Option Case SyntaxKind.ImportsStatement isLeaf = True Return Label.Import Case SyntaxKind.AttributesStatement isLeaf = False Return Label.Attributes Case SyntaxKind.NamespaceBlock isLeaf = False Return Label.NamespaceDeclaration Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock isLeaf = False Return Label.TypeDeclaration Case SyntaxKind.EnumBlock isLeaf = False Return Label.EnumDeclaration Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement isLeaf = False Return Label.DelegateDeclaration Case SyntaxKind.FieldDeclaration isLeaf = False Return Label.FieldDeclaration Case SyntaxKind.VariableDeclarator isLeaf = ignoreVariableDeclarations Return If(ignoreVariableDeclarations, Label.Ignored, Label.FieldVariableDeclarator) Case SyntaxKind.ModifiedIdentifier isLeaf = True Return If(ignoreVariableDeclarations, Label.Ignored, Label.FieldOrParameterName) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock isLeaf = False Return Label.MethodDeclaration Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement isLeaf = False Return Label.PInvokeDeclaration Case SyntaxKind.ConstructorBlock isLeaf = False Return Label.ConstructorDeclaration Case SyntaxKind.OperatorBlock isLeaf = False Return Label.OperatorDeclaration Case SyntaxKind.PropertyBlock isLeaf = False Return Label.PropertyDeclaration Case SyntaxKind.EventBlock isLeaf = False Return Label.CustomEventDeclaration Case SyntaxKind.EnumMemberDeclaration isLeaf = False Return Label.EnumMemberDeclaration Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock isLeaf = False Return Label.AccessorDeclaration Case SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement, SyntaxKind.NamespaceStatement, SyntaxKind.EnumStatement, SyntaxKind.SubStatement, SyntaxKind.SubNewStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement isLeaf = False Return Label.DeclarationStatement Case SyntaxKind.EventStatement isLeaf = False Return Label.EventStatement Case SyntaxKind.TypeParameterList isLeaf = False Return Label.TypeParameterList Case SyntaxKind.TypeParameter isLeaf = False Return Label.TypeParameter Case SyntaxKind.ParameterList isLeaf = False Return Label.ParameterList Case SyntaxKind.Parameter isLeaf = False Return Label.Parameter Case SyntaxKind.AttributeList If nodeOpt IsNot Nothing AndAlso nodeOpt.IsParentKind(SyntaxKind.AttributesStatement) Then isLeaf = False Return Label.AttributeList End If isLeaf = True Return Label.Ignored Case SyntaxKind.Attribute isLeaf = True If nodeOpt IsNot Nothing AndAlso nodeOpt.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then Return Label.Attribute End If Return Label.Ignored Case Else isLeaf = True Return Label.Ignored End Select End Function Protected Overrides Function GetLabel(node As SyntaxNode) As Integer If _matchingLambdas AndAlso (node Is _newRoot OrElse node Is _oldRoot) Then Return Label.LambdaRoot End If Return GetLabelImpl(node) End Function Friend Function GetLabelImpl(node As SyntaxNode) As Label Dim isLeaf As Boolean Return Classify(node.Kind, node, isLeaf, ignoreVariableDeclarations:=False) End Function '' internal for testing Friend Overloads Function HasLabel(kind As SyntaxKind, ignoreVariableDeclarations As Boolean) As Boolean Dim isLeaf As Boolean Return Classify(kind, Nothing, isLeaf, ignoreVariableDeclarations) <> Label.Ignored End Function Protected Overrides ReadOnly Property LabelCount As Integer Get Return Label.Count End Get End Property Protected Overrides Function TiedToAncestor(label As Integer) As Integer Return TiedToAncestor(CType(label, Label)) End Function #End Region #Region "Comparisons" Public Overrides Function ValuesEqual(left As SyntaxNode, right As SyntaxNode) As Boolean Dim ignoreChildFunction As Func(Of SyntaxKind, Boolean) Select Case left.Kind() Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' When comparing a block containing method body statements we need to not ignore ' VariableDeclaration, ModifiedIdentifier, and AsClause children. ' But when comparing field definitions we should ignore VariableDeclaration children. ignoreChildFunction = Function(childKind) HasLabel(childKind, ignoreVariableDeclarations:=True) Case SyntaxKind.AttributesStatement ' Normally attributes and attribute lists are ignored, but for attribute statements ' we need to include them, so just assume they're labelled ignoreChildFunction = Function(childKind) True Case Else If HasChildren(left) Then ignoreChildFunction = Function(childKind) HasLabel(childKind, ignoreVariableDeclarations:=False) Else ignoreChildFunction = Nothing End If End Select Return SyntaxFactory.AreEquivalent(left, right, ignoreChildFunction) End Function Protected Overrides Function TryComputeWeightedDistance(leftNode As SyntaxNode, rightNode As SyntaxNode, ByRef distance As Double) As Boolean Select Case leftNode.Kind Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock, SyntaxKind.WhileBlock Dim getParts = Function(node As SyntaxNode) Select Case node.Kind Case SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Dim block = DirectCast(node, DoLoopBlockSyntax) Return New With {.Begin = CType(block.LoopStatement, StatementSyntax), block.Statements} Case SyntaxKind.WhileBlock Dim block = DirectCast(node, WhileBlockSyntax) Return New With {.Begin = CType(block.WhileStatement, StatementSyntax), block.Statements} Case Else Dim block = DirectCast(node, DoLoopBlockSyntax) Return New With {.Begin = CType(block.DoStatement, StatementSyntax), block.Statements} End Select End Function Dim leftParts = getParts(leftNode) Dim rightParts = getParts(rightNode) distance = ComputeWeightedDistance(leftParts.Begin, leftParts.Statements, rightParts.Begin, rightParts.Statements) Return True Case SyntaxKind.ForBlock Dim leftFor = DirectCast(leftNode, ForOrForEachBlockSyntax) Dim rightFor = DirectCast(rightNode, ForOrForEachBlockSyntax) Dim leftStatement = DirectCast(leftFor.ForOrForEachStatement, ForStatementSyntax) Dim rightStatement = DirectCast(rightFor.ForOrForEachStatement, ForStatementSyntax) distance = ComputeWeightedDistance(leftStatement.ControlVariable, leftFor.ForOrForEachStatement, leftFor.Statements, rightStatement.ControlVariable, rightFor.ForOrForEachStatement, rightFor.Statements) Return True Case SyntaxKind.ForEachBlock Dim leftFor = DirectCast(leftNode, ForOrForEachBlockSyntax) Dim rightFor = DirectCast(rightNode, ForOrForEachBlockSyntax) Dim leftStatement = DirectCast(leftFor.ForOrForEachStatement, ForEachStatementSyntax) Dim rightStatement = DirectCast(rightFor.ForOrForEachStatement, ForEachStatementSyntax) distance = ComputeWeightedDistance(leftStatement.ControlVariable, leftFor.ForOrForEachStatement, leftFor.Statements, rightStatement.ControlVariable, rightFor.ForOrForEachStatement, rightFor.Statements) Return True Case SyntaxKind.UsingBlock Dim leftUsing = DirectCast(leftNode, UsingBlockSyntax) Dim rightUsing = DirectCast(rightNode, UsingBlockSyntax) distance = ComputeWeightedDistance(leftUsing.UsingStatement.Expression, leftUsing.Statements, rightUsing.UsingStatement.Expression, rightUsing.Statements) Return True Case SyntaxKind.WithBlock Dim leftWith = DirectCast(leftNode, WithBlockSyntax) Dim rightWith = DirectCast(rightNode, WithBlockSyntax) distance = ComputeWeightedDistance(leftWith.WithStatement.Expression, leftWith.Statements, rightWith.WithStatement.Expression, rightWith.Statements) Return True Case SyntaxKind.SyncLockBlock Dim leftLock = DirectCast(leftNode, SyncLockBlockSyntax) Dim rightLock = DirectCast(rightNode, SyncLockBlockSyntax) distance = ComputeWeightedDistance(leftLock.SyncLockStatement.Expression, leftLock.Statements, rightLock.SyncLockStatement.Expression, rightLock.Statements) Return True Case SyntaxKind.VariableDeclarator ' For top level syntax a variable declarator is seen for field declarations as we need to treat ' them differently to local declarations, which is what is seen in statement syntax If Not _compareStatementSyntax Then Dim leftIdentifiers = DirectCast(leftNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) Dim rightIdentifiers = DirectCast(rightNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) distance = ComputeDistance(leftIdentifiers, rightIdentifiers) Return True End If distance = ComputeDistance(DirectCast(leftNode, VariableDeclaratorSyntax).Names, DirectCast(rightNode, VariableDeclaratorSyntax).Names) Return True Case SyntaxKind.MultiLineIfBlock, SyntaxKind.SingleLineIfStatement Dim ifParts = Function(node As SyntaxNode) If node.IsKind(SyntaxKind.MultiLineIfBlock) Then Dim part = DirectCast(node, MultiLineIfBlockSyntax) Return New With {part.IfStatement.Condition, part.Statements} Else Dim part = DirectCast(node, SingleLineIfStatementSyntax) Return New With {part.Condition, part.Statements} End If End Function Dim leftIf = ifParts(leftNode) Dim rightIf = ifParts(rightNode) distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statements, rightIf.Condition, rightIf.Statements) Return True Case SyntaxKind.ElseIfBlock Dim leftElseIf = DirectCast(leftNode, ElseIfBlockSyntax) Dim rightElseIf = DirectCast(rightNode, ElseIfBlockSyntax) distance = ComputeWeightedDistance(leftElseIf.ElseIfStatement.Condition, leftElseIf.Statements, rightElseIf.ElseIfStatement.Condition, rightElseIf.Statements) Return True Case SyntaxKind.ElseBlock, SyntaxKind.SingleLineElseClause Dim elseStatements = Function(node As SyntaxNode) If node.IsKind(SyntaxKind.ElseBlock) Then Return DirectCast(node, ElseBlockSyntax).Statements Else Return DirectCast(node, SingleLineElseClauseSyntax).Statements End If End Function Dim leftStatements = elseStatements(leftNode) Dim rightStatements = elseStatements(rightNode) distance = ComputeWeightedDistance(Nothing, leftStatements, Nothing, rightStatements) Return True Case SyntaxKind.CatchBlock Dim leftCatch = DirectCast(leftNode, CatchBlockSyntax) Dim rightCatch = DirectCast(rightNode, CatchBlockSyntax) distance = ComputeWeightedDistance(leftCatch.CatchStatement, leftCatch.Statements, rightCatch.CatchStatement, rightCatch.Statements) Return True Case SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Dim getParts = Function(node As SyntaxNode) Select Case node.Kind Case SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression Dim lambda = DirectCast(node, SingleLineLambdaExpressionSyntax) Return New With {lambda.SubOrFunctionHeader, .Body = lambda.Body.DescendantTokens()} Case Else Dim lambda = DirectCast(node, MultiLineLambdaExpressionSyntax) Return New With {lambda.SubOrFunctionHeader, .Body = GetDescendantTokensIgnoringSeparators(lambda.Statements)} End Select End Function Dim leftParts = getParts(leftNode) Dim rightParts = getParts(rightNode) distance = ComputeWeightedDistanceOfLambdas(leftParts.SubOrFunctionHeader, rightParts.SubOrFunctionHeader, leftParts.Body, rightParts.Body) Return True Case SyntaxKind.VariableDeclarator Dim leftIdentifiers = DirectCast(leftNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) Dim rightIdentifiers = DirectCast(rightNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) distance = ComputeDistance(leftIdentifiers, rightIdentifiers) Return True Case Else Dim leftName As SyntaxNodeOrToken? = TryGetName(leftNode) Dim rightName As SyntaxNodeOrToken? = TryGetName(rightNode) If leftName.HasValue AndAlso rightName.HasValue Then distance = ComputeDistance(leftName.Value, rightName.Value) Return True End If distance = 0 Return False End Select End Function Private Shared Function ComputeWeightedDistanceOfLambdas(leftHeader As LambdaHeaderSyntax, rightHeader As LambdaHeaderSyntax, leftBody As IEnumerable(Of SyntaxToken), rightBody As IEnumerable(Of SyntaxToken)) As Double If leftHeader.Modifiers.Any(SyntaxKind.AsyncKeyword) <> rightHeader.Modifiers.Any(SyntaxKind.AsyncKeyword) Then Return 1.0 End If Dim parameterDistance = ComputeDistance(leftHeader.ParameterList, rightHeader.ParameterList) If leftHeader.AsClause IsNot Nothing OrElse rightHeader.AsClause IsNot Nothing Then Dim asClauseDistance As Double = ComputeDistance(leftHeader.AsClause, rightHeader.AsClause) parameterDistance = parameterDistance * 0.8 + asClauseDistance * 0.2 End If Dim bodyDistance = ComputeDistance(leftBody, rightBody) Return parameterDistance * 0.6 + bodyDistance * 0.4 End Function Private Shared Function ComputeWeightedDistance(leftHeader As SyntaxNode, leftStatements As SyntaxList(Of StatementSyntax), rightHeader As SyntaxNode, rightStatements As SyntaxList(Of StatementSyntax)) As Double Return ComputeWeightedDistance(Nothing, leftHeader, leftStatements, Nothing, rightHeader, rightStatements) End Function Private Shared Function ComputeWeightedDistance(leftControlVariable As SyntaxNode, leftHeader As SyntaxNode, leftStatements As SyntaxList(Of StatementSyntax), rightControlVariable As SyntaxNode, rightHeader As SyntaxNode, rightStatements As SyntaxList(Of StatementSyntax)) As Double Debug.Assert((leftControlVariable Is Nothing) = (rightControlVariable Is Nothing)) Dim headerDistance As Double = ComputeDistance(leftHeader, rightHeader) If leftControlVariable IsNot Nothing Then Dim controlVariableDistance = ComputeDistance(leftControlVariable, rightControlVariable) headerDistance = controlVariableDistance * 0.9 + headerDistance * 0.1 End If Dim statementDistance As Double = ComputeDistance(leftStatements, rightStatements) Dim distance As Double = headerDistance * 0.6 + statementDistance * 0.4 Dim localsDistance As Double If TryComputeLocalsDistance(leftStatements, rightStatements, localsDistance) Then distance = localsDistance * 0.5 + distance * 0.5 End If Return distance End Function Private Shared Function TryComputeLocalsDistance(left As SyntaxList(Of StatementSyntax), right As SyntaxList(Of StatementSyntax), ByRef distance As Double) As Boolean Dim leftLocals As List(Of SyntaxToken) = Nothing Dim rightLocals As List(Of SyntaxToken) = Nothing GetLocalNames(left, leftLocals) GetLocalNames(right, rightLocals) If leftLocals Is Nothing OrElse rightLocals Is Nothing Then distance = 0 Return False End If distance = ComputeDistance(leftLocals, rightLocals) Return True End Function Private Shared Sub GetLocalNames(statements As SyntaxList(Of StatementSyntax), ByRef result As List(Of SyntaxToken)) For Each s In statements If s.IsKind(SyntaxKind.LocalDeclarationStatement) Then For Each declarator In DirectCast(s, LocalDeclarationStatementSyntax).Declarators GetLocalNames(declarator, result) Next End If Next End Sub Private Shared Sub GetLocalNames(localDecl As VariableDeclaratorSyntax, ByRef result As List(Of SyntaxToken)) For Each local In localDecl.Names If result Is Nothing Then result = New List(Of SyntaxToken)() End If result.Add(local.Identifier) Next End Sub Private Shared Function TryGetName(node As SyntaxNode) As SyntaxNodeOrToken? Select Case node.Kind() Case SyntaxKind.OptionStatement Return DirectCast(node, OptionStatementSyntax).OptionKeyword Case SyntaxKind.NamespaceBlock Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).Identifier Case SyntaxKind.ModifiedIdentifier Return DirectCast(node, ModifiedIdentifierSyntax).Identifier Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.Identifier Case SyntaxKind.SubStatement, ' interface methods SyntaxKind.FunctionStatement Return DirectCast(node, MethodStatementSyntax).Identifier Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(node, DeclareStatementSyntax).Identifier Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).SubNewStatement.NewKeyword Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).OperatorStatement.OperatorToken Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).PropertyStatement.Identifier Case SyntaxKind.PropertyStatement ' interface properties Return DirectCast(node, PropertyStatementSyntax).Identifier Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).EventStatement.Identifier Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).Identifier Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).BlockStatement.DeclarationKeyword Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).Identifier Case SyntaxKind.TypeParameter Return DirectCast(node, TypeParameterSyntax).Identifier Case SyntaxKind.StructureConstraint, SyntaxKind.ClassConstraint, SyntaxKind.NewConstraint Return DirectCast(node, SpecialConstraintSyntax).ConstraintKeyword Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier Case SyntaxKind.Attribute Return DirectCast(node, AttributeSyntax).Name Case Else Return Nothing End Select End Function Public Overrides Function GetDistance(oldNode As SyntaxNode, newNode As SyntaxNode) As Double Debug.Assert(GetLabel(oldNode) = GetLabel(newNode) AndAlso GetLabel(oldNode) <> IgnoredNode) If oldNode Is newNode Then Return ExactMatchDist End If Dim weightedDistance As Double If TryComputeWeightedDistance(oldNode, newNode, weightedDistance) Then If weightedDistance = ExactMatchDist AndAlso Not SyntaxFactory.AreEquivalent(oldNode, newNode) Then weightedDistance = EpsilonDist End If Return weightedDistance End If Return ComputeValueDistance(oldNode, newNode) End Function Friend Shared Function ComputeValueDistance(leftNode As SyntaxNode, rightNode As SyntaxNode) As Double If SyntaxFactory.AreEquivalent(leftNode, rightNode) Then Return ExactMatchDist End If Dim distance As Double = ComputeDistance(leftNode, rightNode) Return If(distance = ExactMatchDist, EpsilonDist, distance) End Function Friend Overloads Shared Function ComputeDistance(oldNodeOrToken As SyntaxNodeOrToken, newNodeOrToken As SyntaxNodeOrToken) As Double Debug.Assert(newNodeOrToken.IsToken = oldNodeOrToken.IsToken) Dim distance As Double If oldNodeOrToken.IsToken Then Dim leftToken = oldNodeOrToken.AsToken() Dim rightToken = newNodeOrToken.AsToken() distance = ComputeDistance(leftToken, rightToken) Debug.Assert(Not SyntaxFactory.AreEquivalent(leftToken, rightToken) OrElse distance = ExactMatchDist) Else Dim leftNode = oldNodeOrToken.AsNode() Dim rightNode = newNodeOrToken.AsNode() distance = ComputeDistance(leftNode, rightNode) Debug.Assert(Not SyntaxFactory.AreEquivalent(leftNode, rightNode) OrElse distance = ExactMatchDist) End If Return distance End Function Friend Overloads Shared Function ComputeDistance(Of TSyntaxNode As SyntaxNode)(oldList As SyntaxList(Of TSyntaxNode), newList As SyntaxList(Of TSyntaxNode)) As Double Return ComputeDistance(GetDescendantTokensIgnoringSeparators(oldList), GetDescendantTokensIgnoringSeparators(newList)) End Function Friend Overloads Shared Function ComputeDistance(Of TSyntaxNode As SyntaxNode)(oldList As SeparatedSyntaxList(Of TSyntaxNode), newList As SeparatedSyntaxList(Of TSyntaxNode)) As Double Return ComputeDistance(GetDescendantTokensIgnoringSeparators(oldList), GetDescendantTokensIgnoringSeparators(newList)) End Function ''' <summary> ''' Enumerates tokens of all nodes in the list. ''' </summary> Friend Shared Iterator Function GetDescendantTokensIgnoringSeparators(Of TSyntaxNode As SyntaxNode)(list As SyntaxList(Of TSyntaxNode)) As IEnumerable(Of SyntaxToken) For Each node In list For Each token In node.DescendantTokens() Yield token Next Next End Function ''' <summary> ''' Enumerates tokens of all nodes in the list. Doesn't include separators. ''' </summary> Private Shared Iterator Function GetDescendantTokensIgnoringSeparators(Of TSyntaxNode As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntaxNode)) As IEnumerable(Of SyntaxToken) For Each node In list For Each token In node.DescendantTokens() Yield token Next Next End Function ''' <summary> ''' Calculates the distance between two syntax nodes, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the nodes are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldNode As SyntaxNode, newNode As SyntaxNode) As Double If oldNode Is Nothing OrElse newNode Is Nothing Then Return If(oldNode Is newNode, 0.0, 1.0) End If Return ComputeDistance(oldNode.DescendantTokens(), newNode.DescendantTokens()) End Function ''' <summary> ''' Calculates the distance between two syntax tokens, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the tokens are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldToken As SyntaxToken, newToken As SyntaxToken) As Double Return LongestCommonSubstring.ComputeDistance(oldToken.ValueText, newToken.ValueText) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax tokens, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As IEnumerable(Of SyntaxToken), newTokens As IEnumerable(Of SyntaxToken)) As Double Return ComputeDistance(oldTokens.AsImmutableOrNull(), newTokens.AsImmutableOrNull()) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax tokens, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As ImmutableArray(Of SyntaxToken), newTokens As ImmutableArray(Of SyntaxToken)) As Double Return LcsTokens.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty()) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax nodes, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As IEnumerable(Of SyntaxNode), newTokens As IEnumerable(Of SyntaxNode)) As Double Return ComputeDistance(oldTokens.AsImmutableOrNull(), newTokens.AsImmutableOrNull()) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax nodes, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As ImmutableArray(Of SyntaxNode), newTokens As ImmutableArray(Of SyntaxNode)) As Double Return LcsNodes.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldNodes As IEnumerable(Of SyntaxNode), newNodes As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SequenceEdit) Return LcsNodes.Instance.GetEdits(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit) Return LcsNodes.Instance.GetEdits(oldNodes.NullToEmpty(), newNodes.NullToEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldTokens As IEnumerable(Of SyntaxToken), newTokens As IEnumerable(Of SyntaxToken)) As IEnumerable(Of SequenceEdit) Return LcsTokens.Instance.GetEdits(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldTokens As ImmutableArray(Of SyntaxToken), newTokens As ImmutableArray(Of SyntaxToken)) As IEnumerable(Of SequenceEdit) Return LcsTokens.Instance.GetEdits(oldTokens.NullToEmpty(), newTokens.NullToEmpty()) End Function Private NotInheritable Class LcsTokens Inherits LongestCommonImmutableArraySubsequence(Of SyntaxToken) Friend Shared ReadOnly Instance As LcsTokens = New LcsTokens() Protected Overrides Function Equals(oldElement As SyntaxToken, newElement As SyntaxToken) As Boolean Return SyntaxFactory.AreEquivalent(oldElement, newElement) End Function End Class Private NotInheritable Class LcsNodes Inherits LongestCommonImmutableArraySubsequence(Of SyntaxNode) Friend Shared ReadOnly Instance As LcsNodes = New LcsNodes() Protected Overrides Function Equals(oldElement As SyntaxNode, newElement As SyntaxNode) As Boolean Return SyntaxFactory.AreEquivalent(oldElement, newElement) End Function End Class #End Region End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports Microsoft.CodeAnalysis.Differencing Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.EditAndContinue Friend NotInheritable Class SyntaxComparer Inherits AbstractSyntaxComparer Friend Shared ReadOnly TopLevel As SyntaxComparer = New SyntaxComparer(Nothing, Nothing, Nothing, Nothing, compareStatementSyntax:=False) Friend Shared ReadOnly Statement As SyntaxComparer = New SyntaxComparer(Nothing, Nothing, Nothing, Nothing, compareStatementSyntax:=True) Private ReadOnly _matchingLambdas As Boolean Public Sub New(oldRoot As SyntaxNode, newRoot As SyntaxNode, oldRootChildren As IEnumerable(Of SyntaxNode), newRootChildren As IEnumerable(Of SyntaxNode), Optional matchingLambdas As Boolean = False, Optional compareStatementSyntax As Boolean = False) MyBase.New(oldRoot, newRoot, oldRootChildren, newRootChildren, compareStatementSyntax) _matchingLambdas = matchingLambdas End Sub Protected Overrides Function IsLambdaBodyStatementOrExpression(node As SyntaxNode) As Boolean Return LambdaUtilities.IsLambdaBodyStatementOrExpression(node) End Function #Region "Labels" ' Assumptions: ' - Each listed label corresponds to one or more syntax kinds. ' - Nodes with same labels might produce Update edits, nodes with different labels don't. ' - If IsTiedToParent(label) is true for a label then all its possible parent labels must precede the label. ' (i.e. both MethodDeclaration and TypeDeclaration must precede TypeParameter label). ' - All descendants of a node whose kind is listed here will be ignored regardless of their labels Friend Enum Label ' ' Top Syntax ' CompilationUnit [Option] ' tied to parent Import ' tied to parent Attributes ' tied to parent NamespaceDeclaration TypeDeclaration EnumDeclaration DelegateDeclaration FieldDeclaration ' tied to parent FieldVariableDeclarator ' tied to parent PInvokeDeclaration ' tied to parent MethodDeclaration ' tied to parent ConstructorDeclaration ' tied to parent OperatorDeclaration ' tied to parent PropertyDeclaration ' tied to parent CustomEventDeclaration ' tied to parent EnumMemberDeclaration ' tied to parent AccessorDeclaration ' tied to parent ' Opening statement of a type, method, operator, constructor, property, and accessor. ' We need to represent this node in the graph since attributes, (generic) parameters are its children. ' However, we don't need to have a specialized label for each type of declaration statement since ' they are tied to the parent and each parent has a single declaration statement. DeclarationStatement ' tied to parent ' Event statement is either a child of a custom event or a stand-alone event field declaration. EventStatement ' tied to parent TypeParameterList ' tied to parent TypeParameter ' tied to parent ParameterList ' tied to parent Parameter ' tied to parent FieldOrParameterName ' tied to grand-grandparent (type or method declaration) AttributeList ' tied to parent Attribute ' tied to parent ' ' Statement Syntax ' BodyBlock ' We need to represent sub/function/ctor/accessor/operator declaration ' begin And End statements since they may be active statements. BodyBegin ' tied to parent LambdaRoot TryBlock TryStatement ' tied to parent CatchBlock ' tied to parent CatchStatement ' tied to parent FinallyBlock ' tied to parent FinallyStatement ' tied to parent CatchFilterClause ' tied to parent EndTryStatement ' tied to parent ForBlock ForEachBlock ForEachStatement ' tied to parent ForStatement ' tied to parent ForStepClause ' tied to parent NextStatement ' tied to parent UsingBlock UsingStatement ' tied to parent EndUsingStatement ' tied to parent SyncLockBlock SyncLockStatement ' tied to parent EndSyncLockStatement ' tied to parent WithBlock WithStatement ' tied to parent EndWithStatement ' tied to parent DoWhileBlock DoWhileStatement ' tied to parent EndLoop ' tied to parent WhileOrUntilClause ' tied to parent IfBlock IfStatement ' tied to parent ElseIfBlock ' tied to parent ElseIfStatement ' tied to parent ElseBlock ' tied to parent ElseStatement ' tied to parent EndIfStatement ' tied to parent SelectBlock SelectStatement ' tied to parent CaseBlock ' tied to parent CaseStatement ' tied to parent CaseClause ' tied to parent EndSelectStatement ' tied to parent ReDimStatement ReDimClause ' tied to parent ' Exit Sub|Function|Operator|Property|For|While|Do|Select|Try ExitStatement ' Continue While|Do|For ContinueStatement ' Throw, Throw expr ThrowStatement ErrorStatement ' Return, Return expr ReturnStatement OnErrorStatement ResumeStatement ' GoTo, Stop, End GoToStatement LabelStatement EraseStatement ExpressionStatement AssignmentStatement EventHandlerStatement YieldStatement LocalDeclarationStatement ' tied to parent LocalVariableDeclarator ' tied to parent ' TODO: AwaitExpression Lambda LambdaBodyBegin ' tied to parent QueryExpression AggregateClause ' tied to parent JoinClause ' tied to parent FromClause ' tied to parent WhereClauseLambda ' tied to parent LetClause ' tied to parent SelectClauseLambda ' tied to parent PartitionWhileLambda ' tied to parent PartitionClause ' tied to parent GroupByClause ' tied to parent OrderByClause ' tied to parent CollectionRangeVariable ' tied to parent (FromClause, JoinClause, AggregateClause) ExpressionRangeVariable ' tied to parent (LetClause, SelectClause, GroupByClause keys) ExpressionRangeVariableItems ' tied to parent (GroupByClause items) FunctionAggregationLambda ' tied to parent (JoinClause, GroupByClause, AggregateClause) OrderingLambda ' tied to parent (OrderByClause) JoinConditionLambda ' tied to parent (JoinClause) LocalVariableName ' tied to parent BodyEnd ' tied to parent ' helpers Count Ignored = IgnoredNode End Enum ''' <summary> ''' Return true if it is desirable to report two edits (delete and insert) rather than a move edit ''' when the node changes its parent. ''' </summary> Private Overloads Shared Function TiedToAncestor(label As Label) As Integer Select Case label ' Top level syntax Case Label.Option, Label.Import, Label.Attributes, Label.FieldDeclaration, Label.FieldVariableDeclarator, Label.PInvokeDeclaration, Label.MethodDeclaration, Label.OperatorDeclaration, Label.ConstructorDeclaration, Label.PropertyDeclaration, Label.CustomEventDeclaration, Label.EnumMemberDeclaration, Label.AccessorDeclaration, Label.DeclarationStatement, Label.EventStatement, Label.TypeParameterList, Label.TypeParameter, Label.ParameterList, Label.Parameter, Label.AttributeList, Label.Attribute Return 1 Case Label.FieldOrParameterName Return 3 ' type or method declaration ' Statement syntax Case Label.BodyBegin, Label.LambdaBodyBegin, Label.BodyEnd, Label.TryStatement, Label.CatchBlock, Label.CatchStatement, Label.FinallyBlock, Label.FinallyStatement, Label.CatchFilterClause, Label.EndTryStatement, Label.ForEachStatement, Label.ForStatement, Label.ForStepClause, Label.NextStatement, Label.UsingStatement, Label.EndUsingStatement, Label.SyncLockStatement, Label.EndSyncLockStatement, Label.WithStatement, Label.EndWithStatement, Label.DoWhileStatement, Label.WhileOrUntilClause, Label.EndLoop, Label.IfStatement, Label.ElseIfBlock, Label.ElseIfStatement, Label.ElseBlock, Label.ElseStatement, Label.EndIfStatement, Label.SelectStatement, Label.CaseBlock, Label.CaseStatement, Label.CaseClause, Label.EndSelectStatement, Label.ReDimClause, Label.AggregateClause, Label.JoinClause, Label.FromClause, Label.WhereClauseLambda, Label.LetClause, Label.SelectClauseLambda, Label.PartitionWhileLambda, Label.PartitionClause, Label.GroupByClause, Label.OrderByClause, Label.CollectionRangeVariable, Label.ExpressionRangeVariable, Label.ExpressionRangeVariableItems, Label.FunctionAggregationLambda, Label.OrderingLambda, Label.JoinConditionLambda, Label.LocalDeclarationStatement, Label.LocalVariableDeclarator, Label.LocalVariableName Return 1 Case Else Return 0 End Select Throw New NotImplementedException() End Function Friend Overrides Function Classify(kind As Integer, node As SyntaxNode, ByRef isLeaf As Boolean) As Integer Return Classify(CType(kind, SyntaxKind), node, isLeaf, ignoreVariableDeclarations:=False) End Function ' internal for testing Friend Overloads Function Classify(kind As SyntaxKind, nodeOpt As SyntaxNode, ByRef isLeaf As Boolean, ignoreVariableDeclarations As Boolean) As Label If _compareStatementSyntax Then Return ClassifyStatementSyntax(kind, nodeOpt, isLeaf) End If Return ClassifyTopSytnax(kind, nodeOpt, isLeaf, ignoreVariableDeclarations) End Function Friend Shared Function ClassifyStatementSyntax(kind As SyntaxKind, nodeOpt As SyntaxNode, ByRef isLeaf As Boolean) As Label isLeaf = False Select Case kind Case SyntaxKind.SubBlock, SyntaxKind.ConstructorBlock, SyntaxKind.FunctionBlock, SyntaxKind.OperatorBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return Label.BodyBlock Case SyntaxKind.SubStatement, SyntaxKind.SubNewStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement isLeaf = True Return Label.BodyBegin Case SyntaxKind.SubLambdaHeader, SyntaxKind.FunctionLambdaHeader ' Header is a leaf so that we don't descent into lambda parameters. isLeaf = True Return Label.LambdaBodyBegin Case SyntaxKind.EndSubStatement, SyntaxKind.EndFunctionStatement, SyntaxKind.EndOperatorStatement, SyntaxKind.EndGetStatement, SyntaxKind.EndSetStatement, SyntaxKind.EndAddHandlerStatement, SyntaxKind.EndRemoveHandlerStatement, SyntaxKind.EndRaiseEventStatement isLeaf = True Return Label.BodyEnd Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock, SyntaxKind.WhileBlock Return Label.DoWhileBlock Case SyntaxKind.SimpleDoStatement, SyntaxKind.DoWhileStatement, SyntaxKind.DoUntilStatement, SyntaxKind.WhileStatement Return Label.DoWhileStatement Case SyntaxKind.WhileClause, SyntaxKind.UntilClause Return Label.WhileOrUntilClause Case SyntaxKind.SimpleLoopStatement, SyntaxKind.LoopWhileStatement, SyntaxKind.LoopUntilStatement, SyntaxKind.EndWhileStatement Return Label.EndLoop Case SyntaxKind.ForBlock Return Label.ForBlock Case SyntaxKind.ForEachBlock Return Label.ForEachBlock Case SyntaxKind.ForStatement Return Label.ForStatement Case SyntaxKind.ForEachStatement Return Label.ForEachStatement Case SyntaxKind.ForStepClause Return Label.ForStepClause Case SyntaxKind.NextStatement isLeaf = True Return Label.NextStatement Case SyntaxKind.UsingBlock Return Label.UsingBlock Case SyntaxKind.UsingStatement Return Label.UsingStatement Case SyntaxKind.EndUsingStatement isLeaf = True Return Label.EndUsingStatement Case SyntaxKind.SyncLockBlock Return Label.SyncLockBlock Case SyntaxKind.SyncLockStatement Return Label.SyncLockStatement Case SyntaxKind.EndSyncLockStatement isLeaf = True Return Label.EndSyncLockStatement Case SyntaxKind.WithBlock Return Label.WithBlock Case SyntaxKind.WithStatement Return Label.WithStatement Case SyntaxKind.EndWithStatement isLeaf = True Return Label.EndWithStatement Case SyntaxKind.LocalDeclarationStatement Return Label.LocalDeclarationStatement Case SyntaxKind.VariableDeclarator Return Label.LocalVariableDeclarator Case SyntaxKind.ModifiedIdentifier Return Label.LocalVariableName Case SyntaxKind.MultiLineIfBlock, SyntaxKind.SingleLineIfStatement Return Label.IfBlock Case SyntaxKind.MultiLineIfBlock, SyntaxKind.SingleLineIfStatement Return Label.IfBlock Case SyntaxKind.IfStatement Return Label.IfStatement Case SyntaxKind.ElseIfBlock Return Label.ElseIfBlock Case SyntaxKind.ElseIfStatement Return Label.ElseIfStatement Case SyntaxKind.ElseBlock, SyntaxKind.SingleLineElseClause Return Label.ElseBlock Case SyntaxKind.ElseStatement isLeaf = True Return Label.ElseStatement Case SyntaxKind.EndIfStatement isLeaf = True Return Label.EndIfStatement Case SyntaxKind.TryBlock Return Label.TryBlock Case SyntaxKind.TryBlock Return Label.TryBlock Case SyntaxKind.TryStatement Return Label.TryStatement Case SyntaxKind.CatchBlock Return Label.CatchBlock Case SyntaxKind.CatchStatement Return Label.CatchStatement Case SyntaxKind.FinallyBlock Return Label.FinallyBlock Case SyntaxKind.FinallyStatement Return Label.FinallyStatement Case SyntaxKind.CatchFilterClause Return Label.CatchFilterClause Case SyntaxKind.EndTryStatement isLeaf = True Return Label.EndTryStatement Case SyntaxKind.ErrorStatement isLeaf = True Return Label.ErrorStatement Case SyntaxKind.ThrowStatement Return Label.ThrowStatement Case SyntaxKind.OnErrorGoToZeroStatement, SyntaxKind.OnErrorGoToMinusOneStatement, SyntaxKind.OnErrorGoToLabelStatement, SyntaxKind.OnErrorResumeNextStatement Return Label.OnErrorStatement Case SyntaxKind.ResumeStatement, SyntaxKind.ResumeLabelStatement, SyntaxKind.ResumeNextStatement Return Label.ResumeStatement Case SyntaxKind.SelectBlock Return Label.SelectBlock Case SyntaxKind.SelectStatement Return Label.SelectStatement Case SyntaxKind.CaseBlock, SyntaxKind.CaseElseBlock Return Label.CaseBlock Case SyntaxKind.CaseStatement, SyntaxKind.CaseElseStatement Return Label.CaseStatement Case SyntaxKind.ElseCaseClause, SyntaxKind.SimpleCaseClause, SyntaxKind.RangeCaseClause, SyntaxKind.CaseEqualsClause, SyntaxKind.CaseNotEqualsClause, SyntaxKind.CaseLessThanClause, SyntaxKind.CaseLessThanOrEqualClause, SyntaxKind.CaseGreaterThanOrEqualClause, SyntaxKind.CaseGreaterThanClause Return Label.CaseClause Case SyntaxKind.EndSelectStatement isLeaf = True Return Label.EndSelectStatement Case SyntaxKind.ExitForStatement, SyntaxKind.ExitDoStatement, SyntaxKind.ExitWhileStatement, SyntaxKind.ExitSelectStatement, SyntaxKind.ExitTryStatement, SyntaxKind.ExitSubStatement, SyntaxKind.ExitFunctionStatement, SyntaxKind.ExitOperatorStatement, SyntaxKind.ExitPropertyStatement isLeaf = True Return Label.ExitStatement Case SyntaxKind.ContinueWhileStatement, SyntaxKind.ContinueDoStatement, SyntaxKind.ContinueForStatement isLeaf = True Return Label.ContinueStatement Case SyntaxKind.ReturnStatement Return Label.ReturnStatement Case SyntaxKind.GoToStatement, SyntaxKind.StopStatement, SyntaxKind.EndStatement isLeaf = True Return Label.GoToStatement Case SyntaxKind.LabelStatement isLeaf = True Return Label.LabelStatement Case SyntaxKind.EraseStatement isLeaf = True Return Label.EraseStatement Case SyntaxKind.ExpressionStatement, SyntaxKind.CallStatement Return Label.ExpressionStatement Case SyntaxKind.MidAssignmentStatement, SyntaxKind.SimpleAssignmentStatement, SyntaxKind.AddAssignmentStatement, SyntaxKind.SubtractAssignmentStatement, SyntaxKind.MultiplyAssignmentStatement, SyntaxKind.DivideAssignmentStatement, SyntaxKind.IntegerDivideAssignmentStatement, SyntaxKind.ExponentiateAssignmentStatement, SyntaxKind.LeftShiftAssignmentStatement, SyntaxKind.RightShiftAssignmentStatement, SyntaxKind.ConcatenateAssignmentStatement Return Label.AssignmentStatement Case SyntaxKind.AddHandlerStatement, SyntaxKind.RemoveHandlerStatement, SyntaxKind.RaiseEventStatement Return Label.EventHandlerStatement Case SyntaxKind.ReDimStatement, SyntaxKind.ReDimPreserveStatement Return Label.ReDimStatement Case SyntaxKind.RedimClause Return Label.ReDimClause Case SyntaxKind.YieldStatement Return Label.YieldStatement Case SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Return Label.Lambda Case SyntaxKind.FunctionLambdaHeader, SyntaxKind.SubLambdaHeader ' TODO: Parameters are not mapped? isLeaf = True Return Label.Ignored Case SyntaxKind.QueryExpression Return Label.QueryExpression Case SyntaxKind.WhereClause Return Label.WhereClauseLambda Case SyntaxKind.LetClause Return Label.LetClause Case SyntaxKind.SkipClause, SyntaxKind.TakeClause Return Label.PartitionClause Case SyntaxKind.TakeWhileClause, SyntaxKind.SkipWhileClause Return Label.PartitionWhileLambda Case SyntaxKind.AscendingOrdering, SyntaxKind.DescendingOrdering Return Label.OrderingLambda Case SyntaxKind.FunctionAggregation Return Label.FunctionAggregationLambda Case SyntaxKind.SelectClause Return Label.SelectClauseLambda Case SyntaxKind.GroupByClause Return Label.GroupByClause Case SyntaxKind.OrderByClause Return Label.OrderByClause Case SyntaxKind.SimpleJoinClause, SyntaxKind.GroupJoinClause Return Label.JoinClause Case SyntaxKind.AggregateClause Return Label.AggregateClause Case SyntaxKind.FromClause Return Label.FromClause Case SyntaxKind.ExpressionRangeVariable ' Select, Let, GroupBy ' ' All ERVs need to be included in the map, ' so that we are able to map range variable declarations. ' ' Since we don't distinguish between ERVs that represent a lambda and non-lambda ERVs, ' we need to be handle cases when one maps to the other (and vice versa). ' This is handled in GetCorresondingLambdaBody. ' ' On the other hand we don't want map across lambda body boundaries. ' Hence we use a label for ERVs in Items distinct from one for Keys of a GroupBy clause. ' ' Node that the nodeOpt is Nothing only when comparing nodes for value equality. ' In that case it doesn't matter what label the node has as long as it has some. If nodeOpt IsNot Nothing AndAlso nodeOpt.Parent.IsKind(SyntaxKind.GroupByClause) AndAlso nodeOpt.SpanStart < DirectCast(nodeOpt.Parent, GroupByClauseSyntax).ByKeyword.SpanStart Then Return Label.ExpressionRangeVariableItems Else Return Label.ExpressionRangeVariable End If Case SyntaxKind.CollectionRangeVariable ' From, Aggregate ' ' All CRVs need to be included in the map, ' so that we are able to map range variable declarations. Return Label.CollectionRangeVariable Case SyntaxKind.JoinCondition ' TODO: Return Label.JoinConditionLambda ' TODO: 'Case SyntaxKind.AwaitExpression ' Return Label.AwaitExpression Case SyntaxKind.GenericName ' optimization - no need to dig into type instantiations isLeaf = True Return Label.Ignored Case Else Return Label.Ignored End Select End Function Private Shared Function ClassifyTopSytnax(kind As SyntaxKind, nodeOpt As SyntaxNode, ByRef isLeaf As Boolean, ignoreVariableDeclarations As Boolean) As Label Select Case kind Case SyntaxKind.CompilationUnit isLeaf = False Return Label.CompilationUnit Case SyntaxKind.OptionStatement isLeaf = True Return Label.Option Case SyntaxKind.ImportsStatement isLeaf = True Return Label.Import Case SyntaxKind.AttributesStatement isLeaf = False Return Label.Attributes Case SyntaxKind.NamespaceBlock isLeaf = False Return Label.NamespaceDeclaration Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock isLeaf = False Return Label.TypeDeclaration Case SyntaxKind.EnumBlock isLeaf = False Return Label.EnumDeclaration Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement isLeaf = False Return Label.DelegateDeclaration Case SyntaxKind.FieldDeclaration isLeaf = False Return Label.FieldDeclaration Case SyntaxKind.VariableDeclarator isLeaf = ignoreVariableDeclarations Return If(ignoreVariableDeclarations, Label.Ignored, Label.FieldVariableDeclarator) Case SyntaxKind.ModifiedIdentifier isLeaf = True Return If(ignoreVariableDeclarations, Label.Ignored, Label.FieldOrParameterName) Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock isLeaf = False Return Label.MethodDeclaration Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement isLeaf = False Return Label.PInvokeDeclaration Case SyntaxKind.ConstructorBlock isLeaf = False Return Label.ConstructorDeclaration Case SyntaxKind.OperatorBlock isLeaf = False Return Label.OperatorDeclaration Case SyntaxKind.PropertyBlock isLeaf = False Return Label.PropertyDeclaration Case SyntaxKind.EventBlock isLeaf = False Return Label.CustomEventDeclaration Case SyntaxKind.EnumMemberDeclaration isLeaf = False Return Label.EnumMemberDeclaration Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock isLeaf = False Return Label.AccessorDeclaration Case SyntaxKind.ClassStatement, SyntaxKind.StructureStatement, SyntaxKind.InterfaceStatement, SyntaxKind.ModuleStatement, SyntaxKind.NamespaceStatement, SyntaxKind.EnumStatement, SyntaxKind.SubStatement, SyntaxKind.SubNewStatement, SyntaxKind.FunctionStatement, SyntaxKind.OperatorStatement, SyntaxKind.PropertyStatement, SyntaxKind.GetAccessorStatement, SyntaxKind.SetAccessorStatement, SyntaxKind.AddHandlerAccessorStatement, SyntaxKind.RemoveHandlerAccessorStatement, SyntaxKind.RaiseEventAccessorStatement isLeaf = False Return Label.DeclarationStatement Case SyntaxKind.EventStatement isLeaf = False Return Label.EventStatement Case SyntaxKind.TypeParameterList isLeaf = False Return Label.TypeParameterList Case SyntaxKind.TypeParameter isLeaf = False Return Label.TypeParameter Case SyntaxKind.ParameterList isLeaf = False Return Label.ParameterList Case SyntaxKind.Parameter isLeaf = False Return Label.Parameter Case SyntaxKind.AttributeList If nodeOpt IsNot Nothing AndAlso nodeOpt.IsParentKind(SyntaxKind.AttributesStatement) Then isLeaf = False Return Label.AttributeList End If isLeaf = True Return Label.Ignored Case SyntaxKind.Attribute isLeaf = True If nodeOpt IsNot Nothing AndAlso nodeOpt.Parent.IsParentKind(SyntaxKind.AttributesStatement) Then Return Label.Attribute End If Return Label.Ignored Case Else isLeaf = True Return Label.Ignored End Select End Function Protected Overrides Function GetLabel(node As SyntaxNode) As Integer If _matchingLambdas AndAlso (node Is _newRoot OrElse node Is _oldRoot) Then Return Label.LambdaRoot End If Return GetLabelImpl(node) End Function Friend Function GetLabelImpl(node As SyntaxNode) As Label Dim isLeaf As Boolean Return Classify(node.Kind, node, isLeaf, ignoreVariableDeclarations:=False) End Function '' internal for testing Friend Overloads Function HasLabel(kind As SyntaxKind, ignoreVariableDeclarations As Boolean) As Boolean Dim isLeaf As Boolean Return Classify(kind, Nothing, isLeaf, ignoreVariableDeclarations) <> Label.Ignored End Function Protected Overrides ReadOnly Property LabelCount As Integer Get Return Label.Count End Get End Property Protected Overrides Function TiedToAncestor(label As Integer) As Integer Return TiedToAncestor(CType(label, Label)) End Function #End Region #Region "Comparisons" Public Overrides Function ValuesEqual(left As SyntaxNode, right As SyntaxNode) As Boolean Dim ignoreChildFunction As Func(Of SyntaxKind, Boolean) Select Case left.Kind() Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock, SyntaxKind.ConstructorBlock, SyntaxKind.OperatorBlock, SyntaxKind.PropertyBlock, SyntaxKind.EventBlock, SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock ' When comparing a block containing method body statements we need to not ignore ' VariableDeclaration, ModifiedIdentifier, and AsClause children. ' But when comparing field definitions we should ignore VariableDeclaration children. ignoreChildFunction = Function(childKind) HasLabel(childKind, ignoreVariableDeclarations:=True) Case SyntaxKind.AttributesStatement ' Normally attributes and attribute lists are ignored, but for attribute statements ' we need to include them, so just assume they're labelled ignoreChildFunction = Function(childKind) True Case Else If HasChildren(left) Then ignoreChildFunction = Function(childKind) HasLabel(childKind, ignoreVariableDeclarations:=False) Else ignoreChildFunction = Nothing End If End Select Return SyntaxFactory.AreEquivalent(left, right, ignoreChildFunction) End Function Protected Overrides Function TryComputeWeightedDistance(leftNode As SyntaxNode, rightNode As SyntaxNode, ByRef distance As Double) As Boolean Select Case leftNode.Kind Case SyntaxKind.SimpleDoLoopBlock, SyntaxKind.DoWhileLoopBlock, SyntaxKind.DoUntilLoopBlock, SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock, SyntaxKind.WhileBlock Dim getParts = Function(node As SyntaxNode) Select Case node.Kind Case SyntaxKind.DoLoopWhileBlock, SyntaxKind.DoLoopUntilBlock Dim block = DirectCast(node, DoLoopBlockSyntax) Return New With {.Begin = CType(block.LoopStatement, StatementSyntax), block.Statements} Case SyntaxKind.WhileBlock Dim block = DirectCast(node, WhileBlockSyntax) Return New With {.Begin = CType(block.WhileStatement, StatementSyntax), block.Statements} Case Else Dim block = DirectCast(node, DoLoopBlockSyntax) Return New With {.Begin = CType(block.DoStatement, StatementSyntax), block.Statements} End Select End Function Dim leftParts = getParts(leftNode) Dim rightParts = getParts(rightNode) distance = ComputeWeightedDistance(leftParts.Begin, leftParts.Statements, rightParts.Begin, rightParts.Statements) Return True Case SyntaxKind.ForBlock Dim leftFor = DirectCast(leftNode, ForOrForEachBlockSyntax) Dim rightFor = DirectCast(rightNode, ForOrForEachBlockSyntax) Dim leftStatement = DirectCast(leftFor.ForOrForEachStatement, ForStatementSyntax) Dim rightStatement = DirectCast(rightFor.ForOrForEachStatement, ForStatementSyntax) distance = ComputeWeightedDistance(leftStatement.ControlVariable, leftFor.ForOrForEachStatement, leftFor.Statements, rightStatement.ControlVariable, rightFor.ForOrForEachStatement, rightFor.Statements) Return True Case SyntaxKind.ForEachBlock Dim leftFor = DirectCast(leftNode, ForOrForEachBlockSyntax) Dim rightFor = DirectCast(rightNode, ForOrForEachBlockSyntax) Dim leftStatement = DirectCast(leftFor.ForOrForEachStatement, ForEachStatementSyntax) Dim rightStatement = DirectCast(rightFor.ForOrForEachStatement, ForEachStatementSyntax) distance = ComputeWeightedDistance(leftStatement.ControlVariable, leftFor.ForOrForEachStatement, leftFor.Statements, rightStatement.ControlVariable, rightFor.ForOrForEachStatement, rightFor.Statements) Return True Case SyntaxKind.UsingBlock Dim leftUsing = DirectCast(leftNode, UsingBlockSyntax) Dim rightUsing = DirectCast(rightNode, UsingBlockSyntax) distance = ComputeWeightedDistance(leftUsing.UsingStatement.Expression, leftUsing.Statements, rightUsing.UsingStatement.Expression, rightUsing.Statements) Return True Case SyntaxKind.WithBlock Dim leftWith = DirectCast(leftNode, WithBlockSyntax) Dim rightWith = DirectCast(rightNode, WithBlockSyntax) distance = ComputeWeightedDistance(leftWith.WithStatement.Expression, leftWith.Statements, rightWith.WithStatement.Expression, rightWith.Statements) Return True Case SyntaxKind.SyncLockBlock Dim leftLock = DirectCast(leftNode, SyncLockBlockSyntax) Dim rightLock = DirectCast(rightNode, SyncLockBlockSyntax) distance = ComputeWeightedDistance(leftLock.SyncLockStatement.Expression, leftLock.Statements, rightLock.SyncLockStatement.Expression, rightLock.Statements) Return True Case SyntaxKind.VariableDeclarator ' For top level syntax a variable declarator is seen for field declarations as we need to treat ' them differently to local declarations, which is what is seen in statement syntax If Not _compareStatementSyntax Then Dim leftIdentifiers = DirectCast(leftNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) Dim rightIdentifiers = DirectCast(rightNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) distance = ComputeDistance(leftIdentifiers, rightIdentifiers) Return True End If distance = ComputeDistance(DirectCast(leftNode, VariableDeclaratorSyntax).Names, DirectCast(rightNode, VariableDeclaratorSyntax).Names) Return True Case SyntaxKind.MultiLineIfBlock, SyntaxKind.SingleLineIfStatement Dim ifParts = Function(node As SyntaxNode) If node.IsKind(SyntaxKind.MultiLineIfBlock) Then Dim part = DirectCast(node, MultiLineIfBlockSyntax) Return New With {part.IfStatement.Condition, part.Statements} Else Dim part = DirectCast(node, SingleLineIfStatementSyntax) Return New With {part.Condition, part.Statements} End If End Function Dim leftIf = ifParts(leftNode) Dim rightIf = ifParts(rightNode) distance = ComputeWeightedDistance(leftIf.Condition, leftIf.Statements, rightIf.Condition, rightIf.Statements) Return True Case SyntaxKind.ElseIfBlock Dim leftElseIf = DirectCast(leftNode, ElseIfBlockSyntax) Dim rightElseIf = DirectCast(rightNode, ElseIfBlockSyntax) distance = ComputeWeightedDistance(leftElseIf.ElseIfStatement.Condition, leftElseIf.Statements, rightElseIf.ElseIfStatement.Condition, rightElseIf.Statements) Return True Case SyntaxKind.ElseBlock, SyntaxKind.SingleLineElseClause Dim elseStatements = Function(node As SyntaxNode) If node.IsKind(SyntaxKind.ElseBlock) Then Return DirectCast(node, ElseBlockSyntax).Statements Else Return DirectCast(node, SingleLineElseClauseSyntax).Statements End If End Function Dim leftStatements = elseStatements(leftNode) Dim rightStatements = elseStatements(rightNode) distance = ComputeWeightedDistance(Nothing, leftStatements, Nothing, rightStatements) Return True Case SyntaxKind.CatchBlock Dim leftCatch = DirectCast(leftNode, CatchBlockSyntax) Dim rightCatch = DirectCast(rightNode, CatchBlockSyntax) distance = ComputeWeightedDistance(leftCatch.CatchStatement, leftCatch.Statements, rightCatch.CatchStatement, rightCatch.Statements) Return True Case SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression, SyntaxKind.MultiLineFunctionLambdaExpression, SyntaxKind.MultiLineSubLambdaExpression Dim getParts = Function(node As SyntaxNode) Select Case node.Kind Case SyntaxKind.SingleLineSubLambdaExpression, SyntaxKind.SingleLineFunctionLambdaExpression Dim lambda = DirectCast(node, SingleLineLambdaExpressionSyntax) Return New With {lambda.SubOrFunctionHeader, .Body = lambda.Body.DescendantTokens()} Case Else Dim lambda = DirectCast(node, MultiLineLambdaExpressionSyntax) Return New With {lambda.SubOrFunctionHeader, .Body = GetDescendantTokensIgnoringSeparators(lambda.Statements)} End Select End Function Dim leftParts = getParts(leftNode) Dim rightParts = getParts(rightNode) distance = ComputeWeightedDistanceOfLambdas(leftParts.SubOrFunctionHeader, rightParts.SubOrFunctionHeader, leftParts.Body, rightParts.Body) Return True Case SyntaxKind.VariableDeclarator Dim leftIdentifiers = DirectCast(leftNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) Dim rightIdentifiers = DirectCast(rightNode, VariableDeclaratorSyntax).Names.Select(Function(n) n.Identifier) distance = ComputeDistance(leftIdentifiers, rightIdentifiers) Return True Case Else Dim leftName As SyntaxNodeOrToken? = TryGetName(leftNode) Dim rightName As SyntaxNodeOrToken? = TryGetName(rightNode) If leftName.HasValue AndAlso rightName.HasValue Then distance = ComputeDistance(leftName.Value, rightName.Value) Return True End If distance = 0 Return False End Select End Function Private Shared Function ComputeWeightedDistanceOfLambdas(leftHeader As LambdaHeaderSyntax, rightHeader As LambdaHeaderSyntax, leftBody As IEnumerable(Of SyntaxToken), rightBody As IEnumerable(Of SyntaxToken)) As Double If leftHeader.Modifiers.Any(SyntaxKind.AsyncKeyword) <> rightHeader.Modifiers.Any(SyntaxKind.AsyncKeyword) Then Return 1.0 End If Dim parameterDistance = ComputeDistance(leftHeader.ParameterList, rightHeader.ParameterList) If leftHeader.AsClause IsNot Nothing OrElse rightHeader.AsClause IsNot Nothing Then Dim asClauseDistance As Double = ComputeDistance(leftHeader.AsClause, rightHeader.AsClause) parameterDistance = parameterDistance * 0.8 + asClauseDistance * 0.2 End If Dim bodyDistance = ComputeDistance(leftBody, rightBody) Return parameterDistance * 0.6 + bodyDistance * 0.4 End Function Private Shared Function ComputeWeightedDistance(leftHeader As SyntaxNode, leftStatements As SyntaxList(Of StatementSyntax), rightHeader As SyntaxNode, rightStatements As SyntaxList(Of StatementSyntax)) As Double Return ComputeWeightedDistance(Nothing, leftHeader, leftStatements, Nothing, rightHeader, rightStatements) End Function Private Shared Function ComputeWeightedDistance(leftControlVariable As SyntaxNode, leftHeader As SyntaxNode, leftStatements As SyntaxList(Of StatementSyntax), rightControlVariable As SyntaxNode, rightHeader As SyntaxNode, rightStatements As SyntaxList(Of StatementSyntax)) As Double Debug.Assert((leftControlVariable Is Nothing) = (rightControlVariable Is Nothing)) Dim headerDistance As Double = ComputeDistance(leftHeader, rightHeader) If leftControlVariable IsNot Nothing Then Dim controlVariableDistance = ComputeDistance(leftControlVariable, rightControlVariable) headerDistance = controlVariableDistance * 0.9 + headerDistance * 0.1 End If Dim statementDistance As Double = ComputeDistance(leftStatements, rightStatements) Dim distance As Double = headerDistance * 0.6 + statementDistance * 0.4 Dim localsDistance As Double If TryComputeLocalsDistance(leftStatements, rightStatements, localsDistance) Then distance = localsDistance * 0.5 + distance * 0.5 End If Return distance End Function Private Shared Function TryComputeLocalsDistance(left As SyntaxList(Of StatementSyntax), right As SyntaxList(Of StatementSyntax), ByRef distance As Double) As Boolean Dim leftLocals As List(Of SyntaxToken) = Nothing Dim rightLocals As List(Of SyntaxToken) = Nothing GetLocalNames(left, leftLocals) GetLocalNames(right, rightLocals) If leftLocals Is Nothing OrElse rightLocals Is Nothing Then distance = 0 Return False End If distance = ComputeDistance(leftLocals, rightLocals) Return True End Function Private Shared Sub GetLocalNames(statements As SyntaxList(Of StatementSyntax), ByRef result As List(Of SyntaxToken)) For Each s In statements If s.IsKind(SyntaxKind.LocalDeclarationStatement) Then For Each declarator In DirectCast(s, LocalDeclarationStatementSyntax).Declarators GetLocalNames(declarator, result) Next End If Next End Sub Private Shared Sub GetLocalNames(localDecl As VariableDeclaratorSyntax, ByRef result As List(Of SyntaxToken)) For Each local In localDecl.Names If result Is Nothing Then result = New List(Of SyntaxToken)() End If result.Add(local.Identifier) Next End Sub Private Shared Function TryGetName(node As SyntaxNode) As SyntaxNodeOrToken? Select Case node.Kind() Case SyntaxKind.OptionStatement Return DirectCast(node, OptionStatementSyntax).OptionKeyword Case SyntaxKind.NamespaceBlock Return DirectCast(node, NamespaceBlockSyntax).NamespaceStatement.Name Case SyntaxKind.ClassBlock, SyntaxKind.StructureBlock, SyntaxKind.InterfaceBlock, SyntaxKind.ModuleBlock Return DirectCast(node, TypeBlockSyntax).BlockStatement.Identifier Case SyntaxKind.EnumBlock Return DirectCast(node, EnumBlockSyntax).EnumStatement.Identifier Case SyntaxKind.DelegateFunctionStatement, SyntaxKind.DelegateSubStatement Return DirectCast(node, DelegateStatementSyntax).Identifier Case SyntaxKind.ModifiedIdentifier Return DirectCast(node, ModifiedIdentifierSyntax).Identifier Case SyntaxKind.SubBlock, SyntaxKind.FunctionBlock Return DirectCast(node, MethodBlockSyntax).SubOrFunctionStatement.Identifier Case SyntaxKind.SubStatement, ' interface methods SyntaxKind.FunctionStatement Return DirectCast(node, MethodStatementSyntax).Identifier Case SyntaxKind.DeclareSubStatement, SyntaxKind.DeclareFunctionStatement Return DirectCast(node, DeclareStatementSyntax).Identifier Case SyntaxKind.ConstructorBlock Return DirectCast(node, ConstructorBlockSyntax).SubNewStatement.NewKeyword Case SyntaxKind.OperatorBlock Return DirectCast(node, OperatorBlockSyntax).OperatorStatement.OperatorToken Case SyntaxKind.PropertyBlock Return DirectCast(node, PropertyBlockSyntax).PropertyStatement.Identifier Case SyntaxKind.PropertyStatement ' interface properties Return DirectCast(node, PropertyStatementSyntax).Identifier Case SyntaxKind.EventBlock Return DirectCast(node, EventBlockSyntax).EventStatement.Identifier Case SyntaxKind.EnumMemberDeclaration Return DirectCast(node, EnumMemberDeclarationSyntax).Identifier Case SyntaxKind.GetAccessorBlock, SyntaxKind.SetAccessorBlock, SyntaxKind.AddHandlerAccessorBlock, SyntaxKind.RemoveHandlerAccessorBlock, SyntaxKind.RaiseEventAccessorBlock Return DirectCast(node, AccessorBlockSyntax).BlockStatement.DeclarationKeyword Case SyntaxKind.EventStatement Return DirectCast(node, EventStatementSyntax).Identifier Case SyntaxKind.TypeParameter Return DirectCast(node, TypeParameterSyntax).Identifier Case SyntaxKind.StructureConstraint, SyntaxKind.ClassConstraint, SyntaxKind.NewConstraint Return DirectCast(node, SpecialConstraintSyntax).ConstraintKeyword Case SyntaxKind.Parameter Return DirectCast(node, ParameterSyntax).Identifier.Identifier Case SyntaxKind.Attribute Return DirectCast(node, AttributeSyntax).Name Case Else Return Nothing End Select End Function Public Overrides Function GetDistance(oldNode As SyntaxNode, newNode As SyntaxNode) As Double Debug.Assert(GetLabel(oldNode) = GetLabel(newNode) AndAlso GetLabel(oldNode) <> IgnoredNode) If oldNode Is newNode Then Return ExactMatchDist End If Dim weightedDistance As Double If TryComputeWeightedDistance(oldNode, newNode, weightedDistance) Then If weightedDistance = ExactMatchDist AndAlso Not SyntaxFactory.AreEquivalent(oldNode, newNode) Then weightedDistance = EpsilonDist End If Return weightedDistance End If Return ComputeValueDistance(oldNode, newNode) End Function Friend Shared Function ComputeValueDistance(leftNode As SyntaxNode, rightNode As SyntaxNode) As Double If SyntaxFactory.AreEquivalent(leftNode, rightNode) Then Return ExactMatchDist End If Dim distance As Double = ComputeDistance(leftNode, rightNode) Return If(distance = ExactMatchDist, EpsilonDist, distance) End Function Friend Overloads Shared Function ComputeDistance(oldNodeOrToken As SyntaxNodeOrToken, newNodeOrToken As SyntaxNodeOrToken) As Double Debug.Assert(newNodeOrToken.IsToken = oldNodeOrToken.IsToken) Dim distance As Double If oldNodeOrToken.IsToken Then Dim leftToken = oldNodeOrToken.AsToken() Dim rightToken = newNodeOrToken.AsToken() distance = ComputeDistance(leftToken, rightToken) Debug.Assert(Not SyntaxFactory.AreEquivalent(leftToken, rightToken) OrElse distance = ExactMatchDist) Else Dim leftNode = oldNodeOrToken.AsNode() Dim rightNode = newNodeOrToken.AsNode() distance = ComputeDistance(leftNode, rightNode) Debug.Assert(Not SyntaxFactory.AreEquivalent(leftNode, rightNode) OrElse distance = ExactMatchDist) End If Return distance End Function Friend Overloads Shared Function ComputeDistance(Of TSyntaxNode As SyntaxNode)(oldList As SyntaxList(Of TSyntaxNode), newList As SyntaxList(Of TSyntaxNode)) As Double Return ComputeDistance(GetDescendantTokensIgnoringSeparators(oldList), GetDescendantTokensIgnoringSeparators(newList)) End Function Friend Overloads Shared Function ComputeDistance(Of TSyntaxNode As SyntaxNode)(oldList As SeparatedSyntaxList(Of TSyntaxNode), newList As SeparatedSyntaxList(Of TSyntaxNode)) As Double Return ComputeDistance(GetDescendantTokensIgnoringSeparators(oldList), GetDescendantTokensIgnoringSeparators(newList)) End Function ''' <summary> ''' Enumerates tokens of all nodes in the list. ''' </summary> Friend Shared Iterator Function GetDescendantTokensIgnoringSeparators(Of TSyntaxNode As SyntaxNode)(list As SyntaxList(Of TSyntaxNode)) As IEnumerable(Of SyntaxToken) For Each node In list For Each token In node.DescendantTokens() Yield token Next Next End Function ''' <summary> ''' Enumerates tokens of all nodes in the list. Doesn't include separators. ''' </summary> Private Shared Iterator Function GetDescendantTokensIgnoringSeparators(Of TSyntaxNode As SyntaxNode)(list As SeparatedSyntaxList(Of TSyntaxNode)) As IEnumerable(Of SyntaxToken) For Each node In list For Each token In node.DescendantTokens() Yield token Next Next End Function ''' <summary> ''' Calculates the distance between two syntax nodes, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the nodes are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldNode As SyntaxNode, newNode As SyntaxNode) As Double If oldNode Is Nothing OrElse newNode Is Nothing Then Return If(oldNode Is newNode, 0.0, 1.0) End If Return ComputeDistance(oldNode.DescendantTokens(), newNode.DescendantTokens()) End Function ''' <summary> ''' Calculates the distance between two syntax tokens, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the tokens are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldToken As SyntaxToken, newToken As SyntaxToken) As Double Return LongestCommonSubstring.ComputeDistance(oldToken.ValueText, newToken.ValueText) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax tokens, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As IEnumerable(Of SyntaxToken), newTokens As IEnumerable(Of SyntaxToken)) As Double Return ComputeDistance(oldTokens.AsImmutableOrNull(), newTokens.AsImmutableOrNull()) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax tokens, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As ImmutableArray(Of SyntaxToken), newTokens As ImmutableArray(Of SyntaxToken)) As Double Return LcsTokens.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty()) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax nodes, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As IEnumerable(Of SyntaxNode), newTokens As IEnumerable(Of SyntaxNode)) As Double Return ComputeDistance(oldTokens.AsImmutableOrNull(), newTokens.AsImmutableOrNull()) End Function ''' <summary> ''' Calculates the distance between two sequences of syntax nodes, disregarding trivia. ''' </summary> ''' <remarks> ''' Distance is a number within [0, 1], the smaller the more similar the sequences are. ''' </remarks> Public Overloads Shared Function ComputeDistance(oldTokens As ImmutableArray(Of SyntaxNode), newTokens As ImmutableArray(Of SyntaxNode)) As Double Return LcsNodes.Instance.ComputeDistance(oldTokens.NullToEmpty(), newTokens.NullToEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldNodes As IEnumerable(Of SyntaxNode), newNodes As IEnumerable(Of SyntaxNode)) As IEnumerable(Of SequenceEdit) Return LcsNodes.Instance.GetEdits(oldNodes.AsImmutableOrEmpty(), newNodes.AsImmutableOrEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax nodes to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldNodes As ImmutableArray(Of SyntaxNode), newNodes As ImmutableArray(Of SyntaxNode)) As IEnumerable(Of SequenceEdit) Return LcsNodes.Instance.GetEdits(oldNodes.NullToEmpty(), newNodes.NullToEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldTokens As IEnumerable(Of SyntaxToken), newTokens As IEnumerable(Of SyntaxToken)) As IEnumerable(Of SequenceEdit) Return LcsTokens.Instance.GetEdits(oldTokens.AsImmutableOrEmpty(), newTokens.AsImmutableOrEmpty()) End Function ''' <summary> ''' Calculates the edits that transform one sequence of syntax tokens to another, disregarding trivia. ''' </summary> Public Shared Function GetSequenceEdits(oldTokens As ImmutableArray(Of SyntaxToken), newTokens As ImmutableArray(Of SyntaxToken)) As IEnumerable(Of SequenceEdit) Return LcsTokens.Instance.GetEdits(oldTokens.NullToEmpty(), newTokens.NullToEmpty()) End Function Private NotInheritable Class LcsTokens Inherits LongestCommonImmutableArraySubsequence(Of SyntaxToken) Friend Shared ReadOnly Instance As LcsTokens = New LcsTokens() Protected Overrides Function Equals(oldElement As SyntaxToken, newElement As SyntaxToken) As Boolean Return SyntaxFactory.AreEquivalent(oldElement, newElement) End Function End Class Private NotInheritable Class LcsNodes Inherits LongestCommonImmutableArraySubsequence(Of SyntaxNode) Friend Shared ReadOnly Instance As LcsNodes = New LcsNodes() Protected Overrides Function Equals(oldElement As SyntaxNode, newElement As SyntaxNode) As Boolean Return SyntaxFactory.AreEquivalent(oldElement, newElement) End Function End Class #End Region End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/DriverStateTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // CONSIDER: when the compilation is the same as previous, the syntax trees must also be the same. // if we have a previous state table for a node, we can just short circuit knowing that it is up to date var compilationIsCached = GetLatestStateTableForNode(SharedInputNodes.Compilation).IsCached; // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { if (compilationIsCached && _previousTable._tables.TryGetValue(node, out var previousStateTable)) { _tableBuilder.Add(node, previousStateTable); } else { builders.Add(node.GetBuilder(_previousTable)); } } if (builders.Count == 0) { // bring over the previously cached syntax tree inputs _tableBuilder[SharedInputNodes.SyntaxTrees] = _previousTable._tables[SharedInputNodes.SyntaxTrees]; } else { // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = new Lazy<SyntaxNode>(() => tree.GetRoot(_cancellationToken)); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.ToImmutable()); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis { internal sealed class DriverStateTable { private readonly ImmutableSegmentedDictionary<object, IStateTable> _tables; internal static DriverStateTable Empty { get; } = new DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable>.Empty); private DriverStateTable(ImmutableSegmentedDictionary<object, IStateTable> tables) { _tables = tables; } public NodeStateTable<T> GetStateTableOrEmpty<T>(object input) { if (_tables.TryGetValue(input, out var result)) { return (NodeStateTable<T>)result; } return NodeStateTable<T>.Empty; } public sealed class Builder { private readonly ImmutableSegmentedDictionary<object, IStateTable>.Builder _tableBuilder = ImmutableSegmentedDictionary.CreateBuilder<object, IStateTable>(); private readonly ImmutableArray<ISyntaxInputNode> _syntaxInputNodes; private readonly ImmutableDictionary<ISyntaxInputNode, Exception>.Builder _syntaxExceptions = ImmutableDictionary.CreateBuilder<ISyntaxInputNode, Exception>(); private readonly DriverStateTable _previousTable; private readonly CancellationToken _cancellationToken; internal GeneratorDriverState DriverState { get; } public Compilation Compilation { get; } public Builder(Compilation compilation, GeneratorDriverState driverState, ImmutableArray<ISyntaxInputNode> syntaxInputNodes, CancellationToken cancellationToken = default) { Compilation = compilation; DriverState = driverState; _previousTable = driverState.StateTable; _syntaxInputNodes = syntaxInputNodes; _cancellationToken = cancellationToken; } public IStateTable GetSyntaxInputTable(ISyntaxInputNode syntaxInputNode) { Debug.Assert(_syntaxInputNodes.Contains(syntaxInputNode)); // when we don't have a value for this node, we update all the syntax inputs at once if (!_tableBuilder.ContainsKey(syntaxInputNode)) { // CONSIDER: when the compilation is the same as previous, the syntax trees must also be the same. // if we have a previous state table for a node, we can just short circuit knowing that it is up to date var compilationIsCached = GetLatestStateTableForNode(SharedInputNodes.Compilation).IsCached; // get a builder for each input node var builders = ArrayBuilder<ISyntaxInputBuilder>.GetInstance(_syntaxInputNodes.Length); foreach (var node in _syntaxInputNodes) { if (compilationIsCached && _previousTable._tables.TryGetValue(node, out var previousStateTable)) { _tableBuilder.Add(node, previousStateTable); } else { builders.Add(node.GetBuilder(_previousTable)); } } if (builders.Count == 0) { // bring over the previously cached syntax tree inputs _tableBuilder[SharedInputNodes.SyntaxTrees] = _previousTable._tables[SharedInputNodes.SyntaxTrees]; } else { // update each tree for the builders, sharing the semantic model foreach ((var tree, var state) in GetLatestStateTableForNode(SharedInputNodes.SyntaxTrees)) { var root = new Lazy<SyntaxNode>(() => tree.GetRoot(_cancellationToken)); var model = state != EntryState.Removed ? Compilation.GetSemanticModel(tree) : null; for (int i = 0; i < builders.Count; i++) { try { _cancellationToken.ThrowIfCancellationRequested(); builders[i].VisitTree(root, state, model, _cancellationToken); } catch (UserFunctionException ufe) { // we're evaluating this node ahead of time, so we can't just throw the exception // instead we'll hold onto it, and throw the exception when a downstream node actually // attempts to read the value _syntaxExceptions[builders[i].SyntaxInputNode] = ufe; builders.RemoveAt(i); i--; } } } // save the updated inputs foreach (var builder in builders) { builder.SaveStateAndFree(_tableBuilder); Debug.Assert(_tableBuilder.ContainsKey(builder.SyntaxInputNode)); } } builders.Free(); } // if we don't have an entry for this node, it must have thrown an exception if (!_tableBuilder.ContainsKey(syntaxInputNode)) { throw _syntaxExceptions[syntaxInputNode]; } return _tableBuilder[syntaxInputNode]; } public NodeStateTable<T> GetLatestStateTableForNode<T>(IIncrementalGeneratorNode<T> source) { // if we've already evaluated a node during this build, we can just return the existing result if (_tableBuilder.ContainsKey(source)) { return (NodeStateTable<T>)_tableBuilder[source]; } // get the previous table, if there was one for this node NodeStateTable<T> previousTable = _previousTable.GetStateTableOrEmpty<T>(source); // request the node update its state based on the current driver table and store the new result var newTable = source.UpdateStateTable(this, previousTable, _cancellationToken); _tableBuilder[source] = newTable; return newTable; } public DriverStateTable ToImmutable() { // we can compact the tables at this point, as we'll no longer be using them to determine current state var keys = _tableBuilder.Keys.ToArray(); foreach (var key in keys) { _tableBuilder[key] = _tableBuilder[key].AsCached(); } return new DriverStateTable(_tableBuilder.ToImmutable()); } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Core/ReferenceHighlighting/ReferenceHighlightingViewTaggerProvider.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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { [Export(typeof(IViewTaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(NavigableHighlightTag))] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal partial class ReferenceHighlightingViewTaggerProvider : AsynchronousViewTaggerProvider<NavigableHighlightTag> { // Whenever an edit happens, clear all highlights. When moving the caret, preserve // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.ReferenceHighlighting); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ReferenceHighlightingViewTaggerProvider( IThreadingContext threadingContext, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.ReferenceHighlighting)) { } protected override TaggerDelay EventChangeDelay => TaggerDelay.Medium; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { // Note: we don't listen for OnTextChanged. Text changes to this buffer will get // reported by OnSemanticChanged. return TaggerEventSources.Compose( TaggerEventSources.OnCaretPositionChanged(textView, textView.TextBuffer), TaggerEventSources.OnWorkspaceChanged(subjectBuffer, AsyncListener), TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer)); } protected override SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer) { // With no selection we just use the caret position as expected if (textViewOpt.Selection.IsEmpty) { return textViewOpt.Caret.Position.Point.GetPoint(b => IsSupportedContentType(b.ContentType), PositionAffinity.Successor); } // If there is a selection then it makes more sense for highlighting to apply to the token at the start // of the selection rather than where the caret is, otherwise you can be in a situation like [|count$$|]++ // and it will try to highlight the operator. return textViewOpt.BufferGraph.MapDownToFirstMatch(textViewOpt.Selection.Start.Position, PointTrackingMode.Positive, b => IsSupportedContentType(b.ContentType), PositionAffinity.Successor); } protected override IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer) { // Note: this may return no snapshot spans. We have to be resilient to that // when processing the TaggerContext<>.SpansToTag below. return textViewOpt.BufferGraph.GetTextBuffers(b => IsSupportedContentType(b.ContentType)) .Select(b => b.CurrentSnapshot.GetFullSpan()) .ToList(); } protected override Task ProduceTagsAsync(TaggerContext<NavigableHighlightTag> context) { // NOTE(cyrusn): Normally we'd limit ourselves to producing tags in the span we were // asked about. However, we want to produce all tags here so that the user can actually // navigate between all of them using the appropriate tag navigation commands. If we // don't generate all the tags then the user will cycle through an incorrect subset. if (context.CaretPosition == null) { return Task.CompletedTask; } var caretPosition = context.CaretPosition.Value; if (!Workspace.TryGetWorkspace(caretPosition.Snapshot.AsText().Container, out var workspace)) { return Task.CompletedTask; } // GetSpansToTag may have produced no actual spans to tag. Be resilient to that. var document = context.SpansToTag.FirstOrDefault(vt => vt.SnapshotSpan.Snapshot == caretPosition.Snapshot).Document; if (document == null) { return Task.CompletedTask; } // Don't produce tags if the feature is not enabled. if (!workspace.Options.GetOption(FeatureOnOffOptions.ReferenceHighlighting, document.Project.Language)) { return Task.CompletedTask; } // See if the user is just moving their caret around in an existing tag. If so, we don't // want to actually go recompute things. Note: this only works for containment. If the // user moves their caret to the end of a highlighted reference, we do want to recompute // as they may now be at the start of some other reference that should be highlighted instead. var existingTags = context.GetExistingContainingTags(caretPosition); if (!existingTags.IsEmpty()) { context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>()); return Task.CompletedTask; } // Otherwise, we need to go produce all tags. return ProduceTagsAsync(context, caretPosition, document); } internal static async Task ProduceTagsAsync( TaggerContext<NavigableHighlightTag> context, SnapshotPoint position, Document document) { var cancellationToken = context.CancellationToken; var solution = document.Project.Solution; using (Logger.LogBlock(FunctionId.Tagger_ReferenceHighlighting_TagProducer_ProduceTags, cancellationToken)) { if (document != null) { var service = document.GetLanguageService<IDocumentHighlightsService>(); if (service != null) { // We only want to search inside documents that correspond to the snapshots // we're looking at var documentsToSearch = ImmutableHashSet.CreateRange(context.SpansToTag.Select(vt => vt.Document).WhereNotNull()); var documentHighlightsList = await service.GetDocumentHighlightsAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (documentHighlightsList != null) { foreach (var documentHighlights in documentHighlightsList) { AddTagSpans(context, documentHighlights); } } } } } } private static void AddTagSpans( TaggerContext<NavigableHighlightTag> context, DocumentHighlights documentHighlights) { var cancellationToken = context.CancellationToken; var document = documentHighlights.Document; var textSnapshot = context.SpansToTag.FirstOrDefault(s => s.Document == document).SnapshotSpan.Snapshot; if (textSnapshot == null) { // There is no longer an editor snapshot for this document, so we can't care about the // results. return; } try { foreach (var span in documentHighlights.HighlightSpans) { var tag = GetTag(span); context.AddTag(new TagSpan<NavigableHighlightTag>( textSnapshot.GetSpan(Span.FromBounds(span.TextSpan.Start, span.TextSpan.End)), tag)); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // report NFW and continue. // also, rather than return partial results, return nothing context.ClearTags(); } } private static NavigableHighlightTag GetTag(HighlightSpan span) { switch (span.Kind) { case HighlightSpanKind.WrittenReference: return WrittenReferenceHighlightTag.Instance; case HighlightSpanKind.Definition: return DefinitionHighlightTag.Instance; case HighlightSpanKind.Reference: case HighlightSpanKind.None: default: return ReferenceHighlightTag.Instance; } } private static bool IsSupportedContentType(IContentType contentType) { // This list should match the list of exported content types above return contentType.IsOfType(ContentTypeNames.RoslynContentType) || contentType.IsOfType(ContentTypeNames.XamlContentType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.ComponentModel.Composition; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.DocumentHighlighting; using Microsoft.CodeAnalysis.Editor.Shared.Options; using Microsoft.CodeAnalysis.Editor.Shared.Tagging; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Editor.Tagging; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text.Shared.Extensions; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.ReferenceHighlighting { [Export(typeof(IViewTaggerProvider))] [ContentType(ContentTypeNames.RoslynContentType)] [ContentType(ContentTypeNames.XamlContentType)] [TagType(typeof(NavigableHighlightTag))] [TextViewRole(PredefinedTextViewRoles.Interactive)] internal partial class ReferenceHighlightingViewTaggerProvider : AsynchronousViewTaggerProvider<NavigableHighlightTag> { // Whenever an edit happens, clear all highlights. When moving the caret, preserve // highlights if the caret stays within an existing tag. protected override TaggerCaretChangeBehavior CaretChangeBehavior => TaggerCaretChangeBehavior.RemoveAllTagsOnCaretMoveOutsideOfTag; protected override TaggerTextChangeBehavior TextChangeBehavior => TaggerTextChangeBehavior.RemoveAllTags; protected override IEnumerable<PerLanguageOption2<bool>> PerLanguageOptions => SpecializedCollections.SingletonEnumerable(FeatureOnOffOptions.ReferenceHighlighting); [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public ReferenceHighlightingViewTaggerProvider( IThreadingContext threadingContext, IAsynchronousOperationListenerProvider listenerProvider) : base(threadingContext, listenerProvider.GetListener(FeatureAttribute.ReferenceHighlighting)) { } protected override TaggerDelay EventChangeDelay => TaggerDelay.Medium; protected override ITaggerEventSource CreateEventSource(ITextView textView, ITextBuffer subjectBuffer) { // Note: we don't listen for OnTextChanged. Text changes to this buffer will get // reported by OnSemanticChanged. return TaggerEventSources.Compose( TaggerEventSources.OnCaretPositionChanged(textView, textView.TextBuffer), TaggerEventSources.OnWorkspaceChanged(subjectBuffer, AsyncListener), TaggerEventSources.OnDocumentActiveContextChanged(subjectBuffer)); } protected override SnapshotPoint? GetCaretPoint(ITextView textViewOpt, ITextBuffer subjectBuffer) { // With no selection we just use the caret position as expected if (textViewOpt.Selection.IsEmpty) { return textViewOpt.Caret.Position.Point.GetPoint(b => IsSupportedContentType(b.ContentType), PositionAffinity.Successor); } // If there is a selection then it makes more sense for highlighting to apply to the token at the start // of the selection rather than where the caret is, otherwise you can be in a situation like [|count$$|]++ // and it will try to highlight the operator. return textViewOpt.BufferGraph.MapDownToFirstMatch(textViewOpt.Selection.Start.Position, PointTrackingMode.Positive, b => IsSupportedContentType(b.ContentType), PositionAffinity.Successor); } protected override IEnumerable<SnapshotSpan> GetSpansToTag(ITextView textViewOpt, ITextBuffer subjectBuffer) { // Note: this may return no snapshot spans. We have to be resilient to that // when processing the TaggerContext<>.SpansToTag below. return textViewOpt.BufferGraph.GetTextBuffers(b => IsSupportedContentType(b.ContentType)) .Select(b => b.CurrentSnapshot.GetFullSpan()) .ToList(); } protected override Task ProduceTagsAsync(TaggerContext<NavigableHighlightTag> context) { // NOTE(cyrusn): Normally we'd limit ourselves to producing tags in the span we were // asked about. However, we want to produce all tags here so that the user can actually // navigate between all of them using the appropriate tag navigation commands. If we // don't generate all the tags then the user will cycle through an incorrect subset. if (context.CaretPosition == null) { return Task.CompletedTask; } var caretPosition = context.CaretPosition.Value; if (!Workspace.TryGetWorkspace(caretPosition.Snapshot.AsText().Container, out var workspace)) { return Task.CompletedTask; } // GetSpansToTag may have produced no actual spans to tag. Be resilient to that. var document = context.SpansToTag.FirstOrDefault(vt => vt.SnapshotSpan.Snapshot == caretPosition.Snapshot).Document; if (document == null) { return Task.CompletedTask; } // Don't produce tags if the feature is not enabled. if (!workspace.Options.GetOption(FeatureOnOffOptions.ReferenceHighlighting, document.Project.Language)) { return Task.CompletedTask; } // See if the user is just moving their caret around in an existing tag. If so, we don't // want to actually go recompute things. Note: this only works for containment. If the // user moves their caret to the end of a highlighted reference, we do want to recompute // as they may now be at the start of some other reference that should be highlighted instead. var existingTags = context.GetExistingContainingTags(caretPosition); if (!existingTags.IsEmpty()) { context.SetSpansTagged(SpecializedCollections.EmptyEnumerable<DocumentSnapshotSpan>()); return Task.CompletedTask; } // Otherwise, we need to go produce all tags. return ProduceTagsAsync(context, caretPosition, document); } internal static async Task ProduceTagsAsync( TaggerContext<NavigableHighlightTag> context, SnapshotPoint position, Document document) { var cancellationToken = context.CancellationToken; var solution = document.Project.Solution; using (Logger.LogBlock(FunctionId.Tagger_ReferenceHighlighting_TagProducer_ProduceTags, cancellationToken)) { if (document != null) { var service = document.GetLanguageService<IDocumentHighlightsService>(); if (service != null) { // We only want to search inside documents that correspond to the snapshots // we're looking at var documentsToSearch = ImmutableHashSet.CreateRange(context.SpansToTag.Select(vt => vt.Document).WhereNotNull()); var documentHighlightsList = await service.GetDocumentHighlightsAsync( document, position, documentsToSearch, cancellationToken).ConfigureAwait(false); if (documentHighlightsList != null) { foreach (var documentHighlights in documentHighlightsList) { AddTagSpans(context, documentHighlights); } } } } } } private static void AddTagSpans( TaggerContext<NavigableHighlightTag> context, DocumentHighlights documentHighlights) { var cancellationToken = context.CancellationToken; var document = documentHighlights.Document; var textSnapshot = context.SpansToTag.FirstOrDefault(s => s.Document == document).SnapshotSpan.Snapshot; if (textSnapshot == null) { // There is no longer an editor snapshot for this document, so we can't care about the // results. return; } try { foreach (var span in documentHighlights.HighlightSpans) { var tag = GetTag(span); context.AddTag(new TagSpan<NavigableHighlightTag>( textSnapshot.GetSpan(Span.FromBounds(span.TextSpan.Start, span.TextSpan.End)), tag)); } } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // report NFW and continue. // also, rather than return partial results, return nothing context.ClearTags(); } } private static NavigableHighlightTag GetTag(HighlightSpan span) { switch (span.Kind) { case HighlightSpanKind.WrittenReference: return WrittenReferenceHighlightTag.Instance; case HighlightSpanKind.Definition: return DefinitionHighlightTag.Instance; case HighlightSpanKind.Reference: case HighlightSpanKind.None: default: return ReferenceHighlightTag.Instance; } } private static bool IsSupportedContentType(IContentType contentType) { // This list should match the list of exported content types above return contentType.IsOfType(ContentTypeNames.RoslynContentType) || contentType.IsOfType(ContentTypeNames.XamlContentType); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/Core/Portable/Shared/Utilities/IOUtilities.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.IO; using System.Security; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class IOUtilities { public static void PerformIO(Action action) { PerformIO<object>(() => { action(); return null; }); } public static T PerformIO<T>(Func<T> function, T defaultValue = default) { try { return function(); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static async Task<T> PerformIOAsync<T>(Func<Task<T>> function, T defaultValue = default) { try { return await function().ConfigureAwait(false); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static bool IsNormalIOException(Exception e) { return e is IOException or SecurityException or ArgumentException or UnauthorizedAccessException or NotSupportedException or InvalidOperationException; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.IO; using System.Security; using System.Threading.Tasks; namespace Microsoft.CodeAnalysis.Shared.Utilities { internal static class IOUtilities { public static void PerformIO(Action action) { PerformIO<object>(() => { action(); return null; }); } public static T PerformIO<T>(Func<T> function, T defaultValue = default) { try { return function(); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static async Task<T> PerformIOAsync<T>(Func<Task<T>> function, T defaultValue = default) { try { return await function().ConfigureAwait(false); } catch (Exception e) when (IsNormalIOException(e)) { } return defaultValue; } public static bool IsNormalIOException(Exception e) { return e is IOException or SecurityException or ArgumentException or UnauthorizedAccessException or NotSupportedException or InvalidOperationException; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/Core/Portable/InternalUtilities/OrderedMultiDictionary.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace Roslyn.Utilities { // Note that this is not threadsafe for concurrent reading and writing. internal sealed class OrderedMultiDictionary<K, V> : IEnumerable<KeyValuePair<K, SetWithInsertionOrder<V>>> where K : notnull { private readonly Dictionary<K, SetWithInsertionOrder<V>> _dictionary; private readonly List<K> _keys; public int Count => _dictionary.Count; public IEnumerable<K> Keys => _keys; // Returns an empty set if there is no such key in the dictionary. public SetWithInsertionOrder<V> this[K k] { get { SetWithInsertionOrder<V>? set; return _dictionary.TryGetValue(k, out set) ? set : new SetWithInsertionOrder<V>(); } } public OrderedMultiDictionary() { _dictionary = new Dictionary<K, SetWithInsertionOrder<V>>(); _keys = new List<K>(); } public void Add(K k, V v) { SetWithInsertionOrder<V>? set; if (!_dictionary.TryGetValue(k, out set)) { _keys.Add(k); set = new SetWithInsertionOrder<V>(); } set.Add(v); _dictionary[k] = set; } public void AddRange(K k, IEnumerable<V> values) { foreach (var v in values) { Add(k, v); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<KeyValuePair<K, SetWithInsertionOrder<V>>> GetEnumerator() { foreach (var key in _keys) { yield return new KeyValuePair<K, SetWithInsertionOrder<V>>( key, _dictionary[key]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace Roslyn.Utilities { // Note that this is not threadsafe for concurrent reading and writing. internal sealed class OrderedMultiDictionary<K, V> : IEnumerable<KeyValuePair<K, SetWithInsertionOrder<V>>> where K : notnull { private readonly Dictionary<K, SetWithInsertionOrder<V>> _dictionary; private readonly List<K> _keys; public int Count => _dictionary.Count; public IEnumerable<K> Keys => _keys; // Returns an empty set if there is no such key in the dictionary. public SetWithInsertionOrder<V> this[K k] { get { SetWithInsertionOrder<V>? set; return _dictionary.TryGetValue(k, out set) ? set : new SetWithInsertionOrder<V>(); } } public OrderedMultiDictionary() { _dictionary = new Dictionary<K, SetWithInsertionOrder<V>>(); _keys = new List<K>(); } public void Add(K k, V v) { SetWithInsertionOrder<V>? set; if (!_dictionary.TryGetValue(k, out set)) { _keys.Add(k); set = new SetWithInsertionOrder<V>(); } set.Add(v); _dictionary[k] = set; } public void AddRange(K k, IEnumerable<V> values) { foreach (var v in values) { Add(k, v); } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); public IEnumerator<KeyValuePair<K, SetWithInsertionOrder<V>>> GetEnumerator() { foreach (var key in _keys) { yield return new KeyValuePair<K, SetWithInsertionOrder<V>>( key, _dictionary[key]); } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenCtorInitializers.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 Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenStructCtor Inherits BasicTestBase <Fact()> Public Sub ParameterlessCtor003() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure S1 Public x as integer Public y as integer public Sub New(x as integer) Me.New me.x = x me.y = me.x + 1 end sub end structure Module M1 Sub Main() dim s as new S1() Console.WriteLine(s.x) s.y = 333 s = new S1() Console.WriteLine(s.y) s = new S1(3) Console.WriteLine(s.x) Console.WriteLine(s.y) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 3 4 ]]>).VerifyIL("S1..ctor(Integer)", <![CDATA[ { // Code size 29 (0x1d) .maxstack 3 IL_0000: ldarg.0 IL_0001: initobj "S1" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld "S1.x As Integer" IL_000e: ldarg.0 IL_000f: ldarg.0 IL_0010: ldfld "S1.x As Integer" IL_0015: ldc.i4.1 IL_0016: add.ovf IL_0017: stfld "S1.y As Integer" IL_001c: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor001() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public readonly Property p1 As Integer Public readonly Property p2 As Integer Public Sub New() p1 = 42 p2 = p1 End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldc.i4.s 42 IL_0009: stfld "Program.c1._p1 As Integer" IL_000e: ldarg.0 IL_000f: ldarg.0 IL_0010: call "Function Program.c1.get_p1() As Integer" IL_0015: stfld "Program.c1._p2 As Integer" IL_001a: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor002() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public shared readonly Property p1 As Integer Public shared readonly Property p2 As Integer Shared Sub New() p1 = 42 p2 = p1 End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c1.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: stsfld "Program.c1._p1 As Integer" IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stsfld "Program.c1._p2 As Integer" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor001s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Structure c1 Public readonly Property p1 As Integer Public readonly Property p2 As Integer Public Sub New(dummy as integer) p1 = 42 p2 = p1 End Sub End Structure Sub Main(args As String()) Dim c As New c1(1) System.Console.WriteLine(c.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor(Integer)", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: initobj "Program.c1" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld "Program.c1._p1 As Integer" IL_000f: ldarg.0 IL_0010: ldarg.0 IL_0011: call "Function Program.c1.get_p1() As Integer" IL_0016: stfld "Program.c1._p2 As Integer" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor002s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Structure c1 Public shared readonly Property p1 As Integer Public shared readonly Property p2 As Integer Shared Sub New() p1 = 42 p2 = p1 End Sub End Structure Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c1.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: stsfld "Program.c1._p1 As Integer" IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stsfld "Program.c1._p2 As Integer" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor003() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public readonly Property p1 As Integer Public Sub New() p1 += 42 End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 22 (0x16) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: call "Function Program.c1.get_p1() As Integer" IL_000d: ldc.i4.s 42 IL_000f: add.ovf IL_0010: stfld "Program.c1._p1 As Integer" IL_0015: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor003s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Structure c1 Public readonly Property p1 As Integer Public Sub New(dummy as integer) p1 += 42 End Sub End Structure Sub Main(args As String()) Dim c As New c1(1) System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor(Integer)", <![CDATA[ { // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: initobj "Program.c1" IL_0007: ldarg.0 IL_0008: ldarg.0 IL_0009: call "Function Program.c1.get_p1() As Integer" IL_000e: ldc.i4.s 42 IL_0010: add.ovf IL_0011: stfld "Program.c1._p1 As Integer" IL_0016: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor004() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public shared readonly Property p1 As Integer Shared Sub New() p1 += Goo End Sub End Class function Goo() as integer System.Console.Write("hello") return 42 end function Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[hello42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: call "Function Program.c1.get_p1() As Integer" IL_0005: call "Function Program.Goo() As Integer" IL_000a: add.ovf IL_000b: stsfld "Program.c1._p1 As Integer" IL_0010: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public readonly Property p1 As Integer Public Sub New() goo(p1) End Sub End Class sub goo(byref x as integer) x = 42 end sub Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call "Sub Program.goo(ByRef Integer)" IL_0014: ldarg.0 IL_0015: ldloc.0 IL_0016: stfld "Program.c1._p1 As Integer" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005i() CompileAndVerify( <compilation> <file name="a.vb"> Module Program class c1 Public readonly Property p1 As Integer Public readonly Property p2 As Integer = goo(p1) End class function goo(byref x as integer) x = 42 return 1 end function Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 39 (0x27) .maxstack 4 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: call "Function Program.c1.get_p1() As Integer" IL_000d: stloc.0 IL_000e: ldloca.s V_0 IL_0010: call "Function Program.goo(ByRef Integer) As Object" IL_0015: ldarg.0 IL_0016: ldloc.0 IL_0017: stfld "Program.c1._p1 As Integer" IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0021: stfld "Program.c1._p2 As Integer" IL_0026: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program class c1 Public shared readonly Property p1 As Integer = 3 Public shared readonly p2 As Integer = goo(p1) End class function goo(byref x as integer) x = 42 return 1 end function Sub Main(args As String()) System.Console.WriteLine(c1.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 36 (0x24) .maxstack 2 .locals init (Integer V_0) IL_0000: ldc.i4.3 IL_0001: stsfld "Program.c1._p1 As Integer" IL_0006: call "Function Program.c1.get_p1() As Integer" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call "Function Program.goo(ByRef Integer) As Object" IL_0013: ldloc.0 IL_0014: stsfld "Program.c1._p1 As Integer" IL_0019: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_001e: stsfld "Program.c1.p2 As Integer" IL_0023: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005si() CompileAndVerify( <compilation> <file name="a.vb"> Module Program class c1 Public shared readonly Property p1 As Integer = 3 Public readonly property p2 As Integer = goo(p1) End class function goo(byref x as integer) x = 42 return 1 end function Sub Main(args As String()) dim c as new c1 System.Console.WriteLine(c1.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[3]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call "Function Program.goo(ByRef Integer) As Object" IL_0014: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0019: stfld "Program.c1._p2 As Integer" IL_001e: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor006() CompileAndVerify( <compilation> <file name="a.vb"> option strict off Module Program Class c1 Public readonly Property p1 As Integer Public Sub New() Dim o as object = new Late o.goo(p1) End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub class Late sub goo(byref x as integer) x = 42 end sub end class End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 100 (0x64) .maxstack 10 .locals init (Object() V_0, Boolean() V_1) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: newobj "Sub Program.Late..ctor()" IL_000b: ldnull IL_000c: ldstr "goo" IL_0011: ldc.i4.1 IL_0012: newarr "Object" IL_0017: dup IL_0018: ldc.i4.0 IL_0019: ldarg.0 IL_001a: call "Function Program.c1.get_p1() As Integer" IL_001f: box "Integer" IL_0024: stelem.ref IL_0025: dup IL_0026: stloc.0 IL_0027: ldnull IL_0028: ldnull IL_0029: ldc.i4.1 IL_002a: newarr "Boolean" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i1 IL_0033: dup IL_0034: stloc.1 IL_0035: ldc.i4.1 IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object" IL_003b: pop IL_003c: ldloc.1 IL_003d: ldc.i4.0 IL_003e: ldelem.u1 IL_003f: brfalse.s IL_0063 IL_0041: ldarg.0 IL_0042: ldloc.0 IL_0043: ldc.i4.0 IL_0044: ldelem.ref IL_0045: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_004a: ldtoken "Integer" IL_004f: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_0054: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ChangeType(Object, System.Type) As Object" IL_0059: unbox.any "Integer" IL_005e: stfld "Program.c1._p1 As Integer" IL_0063: ret } ]]>) End Sub <WorkItem(4383, "https://github.com/dotnet/roslyn/issues/4383")> <Fact()> Public Sub DecimalConstInit001() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Console.WriteLine(ClassWithStaticField.Dictionary("String3")) End Sub End Module Public Class ClassWithStaticField Public Const DecimalConstant As Decimal = 375D Private Shared ReadOnly DictionaryField As Dictionary(Of String, Single) = New Dictionary(Of String, Single) From { {"String1", 1.0F}, {"String2", 2.0F}, {"String3", 3.0F} } Public Shared ReadOnly Property Dictionary As Dictionary(Of String, Single) Get Return DictionaryField End Get End Property End Class </file> </compilation>, expectedOutput:=<![CDATA[3]]> ).VerifyIL("ClassWithStaticField..cctor()", <![CDATA[ { // Code size 75 (0x4b) .maxstack 4 IL_0000: ldc.i4 0x177 IL_0005: conv.i8 IL_0006: newobj "Sub Decimal..ctor(Long)" IL_000b: stsfld "ClassWithStaticField.DecimalConstant As Decimal" IL_0010: newobj "Sub System.Collections.Generic.Dictionary(Of String, Single)..ctor()" IL_0015: dup IL_0016: ldstr "String1" IL_001b: ldc.r4 1 IL_0020: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Single).Add(String, Single)" IL_0025: dup IL_0026: ldstr "String2" IL_002b: ldc.r4 2 IL_0030: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Single).Add(String, Single)" IL_0035: dup IL_0036: ldstr "String3" IL_003b: ldc.r4 3 IL_0040: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Single).Add(String, Single)" IL_0045: stsfld "ClassWithStaticField.DictionaryField As System.Collections.Generic.Dictionary(Of String, Single)" IL_004a: ret } ]]>) End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests.Emit Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class CodeGenStructCtor Inherits BasicTestBase <Fact()> Public Sub ParameterlessCtor003() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Structure S1 Public x as integer Public y as integer public Sub New(x as integer) Me.New me.x = x me.y = me.x + 1 end sub end structure Module M1 Sub Main() dim s as new S1() Console.WriteLine(s.x) s.y = 333 s = new S1() Console.WriteLine(s.y) s = new S1(3) Console.WriteLine(s.x) Console.WriteLine(s.y) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[ 0 0 3 4 ]]>).VerifyIL("S1..ctor(Integer)", <![CDATA[ { // Code size 29 (0x1d) .maxstack 3 IL_0000: ldarg.0 IL_0001: initobj "S1" IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld "S1.x As Integer" IL_000e: ldarg.0 IL_000f: ldarg.0 IL_0010: ldfld "S1.x As Integer" IL_0015: ldc.i4.1 IL_0016: add.ovf IL_0017: stfld "S1.y As Integer" IL_001c: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor001() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public readonly Property p1 As Integer Public readonly Property p2 As Integer Public Sub New() p1 = 42 p2 = p1 End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 27 (0x1b) .maxstack 2 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldc.i4.s 42 IL_0009: stfld "Program.c1._p1 As Integer" IL_000e: ldarg.0 IL_000f: ldarg.0 IL_0010: call "Function Program.c1.get_p1() As Integer" IL_0015: stfld "Program.c1._p2 As Integer" IL_001a: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor002() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public shared readonly Property p1 As Integer Public shared readonly Property p2 As Integer Shared Sub New() p1 = 42 p2 = p1 End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c1.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: stsfld "Program.c1._p1 As Integer" IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stsfld "Program.c1._p2 As Integer" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor001s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Structure c1 Public readonly Property p1 As Integer Public readonly Property p2 As Integer Public Sub New(dummy as integer) p1 = 42 p2 = p1 End Sub End Structure Sub Main(args As String()) Dim c As New c1(1) System.Console.WriteLine(c.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor(Integer)", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 IL_0000: ldarg.0 IL_0001: initobj "Program.c1" IL_0007: ldarg.0 IL_0008: ldc.i4.s 42 IL_000a: stfld "Program.c1._p1 As Integer" IL_000f: ldarg.0 IL_0010: ldarg.0 IL_0011: call "Function Program.c1.get_p1() As Integer" IL_0016: stfld "Program.c1._p2 As Integer" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor002s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Structure c1 Public shared readonly Property p1 As Integer Public shared readonly Property p2 As Integer Shared Sub New() p1 = 42 p2 = p1 End Sub End Structure Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c1.p2) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 18 (0x12) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: stsfld "Program.c1._p1 As Integer" IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stsfld "Program.c1._p2 As Integer" IL_0011: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor003() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public readonly Property p1 As Integer Public Sub New() p1 += 42 End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 22 (0x16) .maxstack 3 IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: call "Function Program.c1.get_p1() As Integer" IL_000d: ldc.i4.s 42 IL_000f: add.ovf IL_0010: stfld "Program.c1._p1 As Integer" IL_0015: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor003s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Structure c1 Public readonly Property p1 As Integer Public Sub New(dummy as integer) p1 += 42 End Sub End Structure Sub Main(args As String()) Dim c As New c1(1) System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor(Integer)", <![CDATA[ { // Code size 23 (0x17) .maxstack 3 IL_0000: ldarg.0 IL_0001: initobj "Program.c1" IL_0007: ldarg.0 IL_0008: ldarg.0 IL_0009: call "Function Program.c1.get_p1() As Integer" IL_000e: ldc.i4.s 42 IL_0010: add.ovf IL_0011: stfld "Program.c1._p1 As Integer" IL_0016: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor004() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public shared readonly Property p1 As Integer Shared Sub New() p1 += Goo End Sub End Class function Goo() as integer System.Console.Write("hello") return 42 end function Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[hello42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 17 (0x11) .maxstack 2 IL_0000: call "Function Program.c1.get_p1() As Integer" IL_0005: call "Function Program.Goo() As Integer" IL_000a: add.ovf IL_000b: stsfld "Program.c1._p1 As Integer" IL_0010: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005() CompileAndVerify( <compilation> <file name="a.vb"> Module Program Class c1 Public readonly Property p1 As Integer Public Sub New() goo(p1) End Sub End Class sub goo(byref x as integer) x = 42 end sub Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 28 (0x1c) .maxstack 2 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call "Sub Program.goo(ByRef Integer)" IL_0014: ldarg.0 IL_0015: ldloc.0 IL_0016: stfld "Program.c1._p1 As Integer" IL_001b: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005i() CompileAndVerify( <compilation> <file name="a.vb"> Module Program class c1 Public readonly Property p1 As Integer Public readonly Property p2 As Integer = goo(p1) End class function goo(byref x as integer) x = 42 return 1 end function Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 39 (0x27) .maxstack 4 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: ldarg.0 IL_0008: call "Function Program.c1.get_p1() As Integer" IL_000d: stloc.0 IL_000e: ldloca.s V_0 IL_0010: call "Function Program.goo(ByRef Integer) As Object" IL_0015: ldarg.0 IL_0016: ldloc.0 IL_0017: stfld "Program.c1._p1 As Integer" IL_001c: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0021: stfld "Program.c1._p2 As Integer" IL_0026: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005s() CompileAndVerify( <compilation> <file name="a.vb"> Module Program class c1 Public shared readonly Property p1 As Integer = 3 Public shared readonly p2 As Integer = goo(p1) End class function goo(byref x as integer) x = 42 return 1 end function Sub Main(args As String()) System.Console.WriteLine(c1.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..cctor()", <![CDATA[ { // Code size 36 (0x24) .maxstack 2 .locals init (Integer V_0) IL_0000: ldc.i4.3 IL_0001: stsfld "Program.c1._p1 As Integer" IL_0006: call "Function Program.c1.get_p1() As Integer" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call "Function Program.goo(ByRef Integer) As Object" IL_0013: ldloc.0 IL_0014: stsfld "Program.c1._p1 As Integer" IL_0019: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_001e: stsfld "Program.c1.p2 As Integer" IL_0023: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor005si() CompileAndVerify( <compilation> <file name="a.vb"> Module Program class c1 Public shared readonly Property p1 As Integer = 3 Public readonly property p2 As Integer = goo(p1) End class function goo(byref x as integer) x = 42 return 1 end function Sub Main(args As String()) dim c as new c1 System.Console.WriteLine(c1.p1) End Sub End Module </file> </compilation>, expectedOutput:=<![CDATA[3]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 31 (0x1f) .maxstack 2 .locals init (Integer V_0) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: ldarg.0 IL_0007: call "Function Program.c1.get_p1() As Integer" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call "Function Program.goo(ByRef Integer) As Object" IL_0014: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ToInteger(Object) As Integer" IL_0019: stfld "Program.c1._p2 As Integer" IL_001e: ret } ]]>) End Sub <Fact()> Public Sub ReadOnlyAutopropInCtor006() CompileAndVerify( <compilation> <file name="a.vb"> option strict off Module Program Class c1 Public readonly Property p1 As Integer Public Sub New() Dim o as object = new Late o.goo(p1) End Sub End Class Sub Main(args As String()) Dim c As New c1 System.Console.WriteLine(c.p1) End Sub class Late sub goo(byref x as integer) x = 42 end sub end class End Module </file> </compilation>, expectedOutput:=<![CDATA[42]]> ).VerifyIL("Program.c1..ctor()", <![CDATA[ { // Code size 100 (0x64) .maxstack 10 .locals init (Object() V_0, Boolean() V_1) IL_0000: ldarg.0 IL_0001: call "Sub Object..ctor()" IL_0006: newobj "Sub Program.Late..ctor()" IL_000b: ldnull IL_000c: ldstr "goo" IL_0011: ldc.i4.1 IL_0012: newarr "Object" IL_0017: dup IL_0018: ldc.i4.0 IL_0019: ldarg.0 IL_001a: call "Function Program.c1.get_p1() As Integer" IL_001f: box "Integer" IL_0024: stelem.ref IL_0025: dup IL_0026: stloc.0 IL_0027: ldnull IL_0028: ldnull IL_0029: ldc.i4.1 IL_002a: newarr "Boolean" IL_002f: dup IL_0030: ldc.i4.0 IL_0031: ldc.i4.1 IL_0032: stelem.i1 IL_0033: dup IL_0034: stloc.1 IL_0035: ldc.i4.1 IL_0036: call "Function Microsoft.VisualBasic.CompilerServices.NewLateBinding.LateCall(Object, System.Type, String, Object(), String(), System.Type(), Boolean(), Boolean) As Object" IL_003b: pop IL_003c: ldloc.1 IL_003d: ldc.i4.0 IL_003e: ldelem.u1 IL_003f: brfalse.s IL_0063 IL_0041: ldarg.0 IL_0042: ldloc.0 IL_0043: ldc.i4.0 IL_0044: ldelem.ref IL_0045: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object" IL_004a: ldtoken "Integer" IL_004f: call "Function System.Type.GetTypeFromHandle(System.RuntimeTypeHandle) As System.Type" IL_0054: call "Function Microsoft.VisualBasic.CompilerServices.Conversions.ChangeType(Object, System.Type) As Object" IL_0059: unbox.any "Integer" IL_005e: stfld "Program.c1._p1 As Integer" IL_0063: ret } ]]>) End Sub <WorkItem(4383, "https://github.com/dotnet/roslyn/issues/4383")> <Fact()> Public Sub DecimalConstInit001() CompileAndVerify( <compilation> <file name="a.vb"> Imports System Imports System.Collections.Generic Module Module1 Sub Main() Console.WriteLine(ClassWithStaticField.Dictionary("String3")) End Sub End Module Public Class ClassWithStaticField Public Const DecimalConstant As Decimal = 375D Private Shared ReadOnly DictionaryField As Dictionary(Of String, Single) = New Dictionary(Of String, Single) From { {"String1", 1.0F}, {"String2", 2.0F}, {"String3", 3.0F} } Public Shared ReadOnly Property Dictionary As Dictionary(Of String, Single) Get Return DictionaryField End Get End Property End Class </file> </compilation>, expectedOutput:=<![CDATA[3]]> ).VerifyIL("ClassWithStaticField..cctor()", <![CDATA[ { // Code size 75 (0x4b) .maxstack 4 IL_0000: ldc.i4 0x177 IL_0005: conv.i8 IL_0006: newobj "Sub Decimal..ctor(Long)" IL_000b: stsfld "ClassWithStaticField.DecimalConstant As Decimal" IL_0010: newobj "Sub System.Collections.Generic.Dictionary(Of String, Single)..ctor()" IL_0015: dup IL_0016: ldstr "String1" IL_001b: ldc.r4 1 IL_0020: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Single).Add(String, Single)" IL_0025: dup IL_0026: ldstr "String2" IL_002b: ldc.r4 2 IL_0030: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Single).Add(String, Single)" IL_0035: dup IL_0036: ldstr "String3" IL_003b: ldc.r4 3 IL_0040: callvirt "Sub System.Collections.Generic.Dictionary(Of String, Single).Add(String, Single)" IL_0045: stsfld "ClassWithStaticField.DictionaryField As System.Collections.Generic.Dictionary(Of String, Single)" IL_004a: ret } ]]>) End Sub End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/VisualBasicTest/ReplaceDocCommentTextWithTag/ReplaceDocCommentTextWithTagTests.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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ReplaceDocCommentTextWithTag Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ReplaceDocCommentTextWithTag Public Class ReplaceDocCommentTextWithTagTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(Workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicReplaceDocCommentTextWithTagCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [||]Nothing. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Nothing""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfKeywordCapitalized() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword Shared[||]. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Shared""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestEndOfKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword True[||]. class C(Of TKey) end class", " ''' Testing keyword <see langword=""True""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestEndOfKeyword_NewLineFollowing() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword MustInherit[||] class C(Of TKey) end class", " ''' Testing keyword <see langword=""MustInherit""/> class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestSelectedKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [|Async|]. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Async""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestInsideKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword Aw[||]ait. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Await""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestNotInsideKeywordIfNonEmptySpan() As Task Await TestMissingAsync( " ''' TKey must implement the System.IDisposable int[|erf|]ace class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Start() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the [||]System.IDisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Mid1() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the System[||].IDisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Mid2() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the System.[||]IDisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_End() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the System.IDisposable[||] interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_CaseInsensitive() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the [||]system.idisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""system.idisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Selected() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the [|System.IDisposable|] interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestTypeParameterReference() As Task Await TestInRegularAndScriptAsync( " ''' [||]TKey must implement the System.IDisposable interface. class C(Of TKey) end class", " ''' <typeparamref name=""TKey""/> must implement the System.IDisposable interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestCanSeeInnerMethod() As Task Await TestInRegularAndScriptAsync( " ''' Use WriteLine[||] as a Console.WriteLine replacement class C sub WriteLine(Of TKey)(value as TKey) end sub end class", " ''' Use <see cref=""WriteLine""/> as a Console.WriteLine replacement class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestNotOnMispelledName() As Task Await TestMissingAsync( " ''' Use WriteLine1[||] as a Console.WriteLine replacement class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodTypeParameterSymbol() As Task Await TestInRegularAndScriptAsync( " class C ''' value has type TKey[||] so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class", " class C ''' value has type <typeparamref name=""TKey""/> so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodTypeParameterSymbol_CaseInsensitive() As Task Await TestInRegularAndScriptAsync( " class C ''' value has type TKey[||] so we don't box primitives. sub WriteLine(Of tkey)(value as TKey) end sub end class", " class C ''' value has type <typeparamref name=""TKey""/> so we don't box primitives. sub WriteLine(Of tkey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodTypeParameterSymbol_EmptyBody() As Task Await TestInRegularAndScriptAsync( " interface I ''' value has type TKey[||] so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface", " interface I ''' value has type <typeparamref name=""TKey""/> so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodParameterSymbol() As Task Await TestInRegularAndScriptAsync( " class C ''' value[||] has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class", " class C ''' <paramref name=""value""/> has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodParameterSymbol_CaseInsensitive() As Task Await TestInRegularAndScriptAsync( " class C ''' value[||] has type TKey so we don't box primitives. sub WriteLine(Of TKey)(Value as TKey) end sub end class", " class C ''' <paramref name=""value""/> has type TKey so we don't box primitives. sub WriteLine(Of TKey)(Value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodParameterSymbol_EmptyBody() As Task Await TestInRegularAndScriptAsync( " interface I ''' value[||] has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface", " interface I ''' <paramref name=""value""/> has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface") End Function <WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestNotApplicableKeyword() As Task Await TestMissingAsync( " ''' Testing keyword interf[||]ace class C(Of TKey) end class") End Function <WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestInXMLAttribute() As Task Await TestMissingAsync( " ''' Testing keyword inside <see langword=""Noth[||]ing""> class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestInXMLAttribute2() As Task Await TestMissingAsync( " ''' Testing keyword inside <see langword=""Not[||]hing"" class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMyBase() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [||]MyBase. class C(Of TKey) end class", " ''' Testing keyword <see langword=""MyBase""/>. class C(Of TKey) end class") End Function <WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMyClass() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [||]MyClass. class C(Of TKey) end class", " ''' Testing keyword <see langword=""MyClass""/>. class C(Of TKey) end class") 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.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.ReplaceDocCommentTextWithTag Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ReplaceDocCommentTextWithTag Public Class ReplaceDocCommentTextWithTagTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(Workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicReplaceDocCommentTextWithTagCodeRefactoringProvider() End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [||]Nothing. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Nothing""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfKeywordCapitalized() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword Shared[||]. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Shared""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestEndOfKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword True[||]. class C(Of TKey) end class", " ''' Testing keyword <see langword=""True""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestEndOfKeyword_NewLineFollowing() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword MustInherit[||] class C(Of TKey) end class", " ''' Testing keyword <see langword=""MustInherit""/> class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestSelectedKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [|Async|]. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Async""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestInsideKeyword() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword Aw[||]ait. class C(Of TKey) end class", " ''' Testing keyword <see langword=""Await""/>. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestNotInsideKeywordIfNonEmptySpan() As Task Await TestMissingAsync( " ''' TKey must implement the System.IDisposable int[|erf|]ace class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Start() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the [||]System.IDisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Mid1() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the System[||].IDisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Mid2() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the System.[||]IDisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_End() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the System.IDisposable[||] interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_CaseInsensitive() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the [||]system.idisposable interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""system.idisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestStartOfFullyQualifiedTypeName_Selected() As Task Await TestInRegularAndScriptAsync( " ''' TKey must implement the [|System.IDisposable|] interface. class C(Of TKey) end class", " ''' TKey must implement the <see cref=""System.IDisposable""/> interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestTypeParameterReference() As Task Await TestInRegularAndScriptAsync( " ''' [||]TKey must implement the System.IDisposable interface. class C(Of TKey) end class", " ''' <typeparamref name=""TKey""/> must implement the System.IDisposable interface. class C(Of TKey) end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestCanSeeInnerMethod() As Task Await TestInRegularAndScriptAsync( " ''' Use WriteLine[||] as a Console.WriteLine replacement class C sub WriteLine(Of TKey)(value as TKey) end sub end class", " ''' Use <see cref=""WriteLine""/> as a Console.WriteLine replacement class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestNotOnMispelledName() As Task Await TestMissingAsync( " ''' Use WriteLine1[||] as a Console.WriteLine replacement class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodTypeParameterSymbol() As Task Await TestInRegularAndScriptAsync( " class C ''' value has type TKey[||] so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class", " class C ''' value has type <typeparamref name=""TKey""/> so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodTypeParameterSymbol_CaseInsensitive() As Task Await TestInRegularAndScriptAsync( " class C ''' value has type TKey[||] so we don't box primitives. sub WriteLine(Of tkey)(value as TKey) end sub end class", " class C ''' value has type <typeparamref name=""TKey""/> so we don't box primitives. sub WriteLine(Of tkey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodTypeParameterSymbol_EmptyBody() As Task Await TestInRegularAndScriptAsync( " interface I ''' value has type TKey[||] so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface", " interface I ''' value has type <typeparamref name=""TKey""/> so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodParameterSymbol() As Task Await TestInRegularAndScriptAsync( " class C ''' value[||] has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class", " class C ''' <paramref name=""value""/> has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodParameterSymbol_CaseInsensitive() As Task Await TestInRegularAndScriptAsync( " class C ''' value[||] has type TKey so we don't box primitives. sub WriteLine(Of TKey)(Value as TKey) end sub end class", " class C ''' <paramref name=""value""/> has type TKey so we don't box primitives. sub WriteLine(Of TKey)(Value as TKey) end sub end class") End Function <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMethodParameterSymbol_EmptyBody() As Task Await TestInRegularAndScriptAsync( " interface I ''' value[||] has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface", " interface I ''' <paramref name=""value""/> has type TKey so we don't box primitives. sub WriteLine(Of TKey)(value as TKey) end interface") End Function <WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestNotApplicableKeyword() As Task Await TestMissingAsync( " ''' Testing keyword interf[||]ace class C(Of TKey) end class") End Function <WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestInXMLAttribute() As Task Await TestMissingAsync( " ''' Testing keyword inside <see langword=""Noth[||]ing""> class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <WorkItem(22278, "https://github.com/dotnet/roslyn/issues/22278")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestInXMLAttribute2() As Task Await TestMissingAsync( " ''' Testing keyword inside <see langword=""Not[||]hing"" class C sub WriteLine(Of TKey)(value as TKey) end sub end class") End Function <WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMyBase() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [||]MyBase. class C(Of TKey) end class", " ''' Testing keyword <see langword=""MyBase""/>. class C(Of TKey) end class") End Function <WorkItem(38370, "https://github.com/dotnet/roslyn/issues/38370")> <Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceDocCommentTextWithTag)> Public Async Function TestMyClass() As Task Await TestInRegularAndScriptAsync( " ''' Testing keyword [||]MyClass. class C(Of TKey) end class", " ''' Testing keyword <see langword=""MyClass""/>. class C(Of TKey) end class") End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Portable/BoundTree/BoundObjectCreationExpressionBase.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 Partial Friend Class BoundObjectCreationExpressionBase #If DEBUG Then Private Sub Validate() Debug.Assert(InitializerOpt Is Nothing OrElse TypeSymbol.Equals(InitializerOpt.Type, Type, TypeCompareKind.ConsiderEverything)) End Sub #End If 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 Partial Friend Class BoundObjectCreationExpressionBase #If DEBUG Then Private Sub Validate() Debug.Assert(InitializerOpt Is Nothing OrElse TypeSymbol.Equals(InitializerOpt.Type, Type, TypeCompareKind.ConsiderEverything)) End Sub #End If End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Test/Symbol/SymbolsTests/Metadata/WinMdEventTest.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.Linq Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Public Class WinMdEventTest Inherits BasicTestBase Private ReadOnly _eventInterfaceILTemplate As String = <![CDATA[ .class interface public abstract auto ansi {0} {{ .method public hidebysig newslot specialname abstract virtual instance void add_Normal(class [mscorlib]System.Action 'value') cil managed {{ }} .method public hidebysig newslot specialname abstract virtual instance void remove_Normal(class [mscorlib]System.Action 'value') cil managed {{ }} .method public hidebysig newslot specialname abstract virtual instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_WinRT([in] class [mscorlib]System.Action 'value') cil managed {{ }} .method public hidebysig newslot specialname abstract virtual instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed {{ }} .event class [mscorlib]System.Action Normal {{ .addon instance void {0}::add_Normal(class [mscorlib]System.Action) .removeon instance void {0}::remove_Normal(class [mscorlib]System.Action) }} .event class [mscorlib]System.Action WinRT {{ .addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken {0}::add_WinRT(class [mscorlib]System.Action) .removeon instance void {0}::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) }} }} // end of class {0} ]]>.Value Private ReadOnly _eventLibRef As MetadataReference Private ReadOnly _dynamicCommonSrc As XElement = <compilation> <file name="dynamic_common.vb"> <![CDATA[ Imports System.Runtime.InteropServices.WindowsRuntime Imports EventLibrary Public Partial Class A Implements I Public Event d1 As voidVoidDelegate Implements I.d1 Public Event d2 As voidStringDelegate Implements I.d2 Public Event d3 As voidDynamicDelegate Implements I.d3 Public Event d4 As voidDelegateDelegate Implements I.d4 End Class Public Partial Class B Implements I Private voidTable As New EventRegistrationTokenTable(Of voidVoidDelegate)() Private voidStringTable As New EventRegistrationTokenTable(Of voidStringDelegate)() Private voidDynamicTable As New EventRegistrationTokenTable(Of voidDynamicDelegate)() Private voidDelegateTable As New EventRegistrationTokenTable(Of voidDelegateDelegate)() Public Custom Event d1 As voidVoidDelegate Implements I.d1 AddHandler(value As voidVoidDelegate) Return voidTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent() End RaiseEvent End Event Public Custom Event d2 As voidStringDelegate Implements I.d2 AddHandler(value As voidStringDelegate) Return voidStringTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidStringTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent(s As String) End RaiseEvent End Event Public Custom Event d3 As voidDynamicDelegate Implements I.d3 AddHandler(value As voidDynamicDelegate) Return voidDynamicTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidDynamicTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent(d As Object) End RaiseEvent End Event Public Custom Event d4 As voidDelegateDelegate Implements I.d4 AddHandler(value As voidDelegateDelegate) Return voidDelegateTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidDelegateTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent([delegate] As voidVoidDelegate) End RaiseEvent End Event End Class ]]> </file> </compilation> Public Sub New() ' The following two libraries are shrunk code pulled from ' corresponding files in the csharp5 legacy tests Dim eventLibSrc = <compilation><file name="EventLibrary.vb"> <![CDATA[ Namespace EventLibrary Public Delegate Sub voidVoidDelegate() Public Delegate Sub voidStringDelegate(s As String) Public Delegate Sub voidDynamicDelegate(d As Object) Public Delegate Sub voidDelegateDelegate([delegate] As voidVoidDelegate) Public Interface I Event d1 As voidVoidDelegate Event d2 As voidStringDelegate Event d3 As voidDynamicDelegate Event d4 As voidDelegateDelegate End Interface End Namespace ]]> </file></compilation> _eventLibRef = CreateEmptyCompilationWithReferences( eventLibSrc, references:={MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929}, options:=TestOptions.ReleaseWinMD).EmitToImageReference() End Sub <Fact()> Public Sub WinMdExternalEventTests() Dim src = <compilation><file name="c.vb"> <![CDATA[ Imports EventLibrary Class C Sub Main() Dim a = new A() Dim b = new B() Dim void = Sub() End Sub Dim str = Sub(s As String) End Sub Dim dyn = Sub(d As Object) End Sub Dim del = Sub([delegate] As voidVoidDelegate) End Sub AddHandler a.d1, void AddHandler a.d2, str AddHandler a.d3, dyn AddHandler a.d4, del RemoveHandler a.d1, void RemoveHandler a.d2, str RemoveHandler a.d3, dyn RemoveHandler a.d4, del AddHandler b.d1, void AddHandler b.d2, str AddHandler b.d3, dyn AddHandler b.d4, del RemoveHandler b.d1, void RemoveHandler b.d2, str RemoveHandler b.d3, dyn RemoveHandler b.d4, del End Sub End Class ]]> </file></compilation> Dim dynamicCommonRef As MetadataReference = CreateEmptyCompilationWithReferences( _dynamicCommonSrc, references:={ MscorlibRef_v4_0_30316_17626, _eventLibRef}, options:=TestOptions.ReleaseModule).EmitToImageReference() Dim verifier = CompileAndVerifyOnWin8Only( src, allReferences:={ MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929, CSharpRef, _eventLibRef, dynamicCommonRef}) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 931 (0x3a3) .maxstack 4 .locals init (A V_0, //a B V_1, //b VB$AnonymousDelegate_0 V_2, //void VB$AnonymousDelegate_1(Of String) V_3, //str VB$AnonymousDelegate_2(Of Object) V_4, //dyn VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_5, //del VB$AnonymousDelegate_0 V_6, VB$AnonymousDelegate_1(Of String) V_7, VB$AnonymousDelegate_2(Of Object) V_8, VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_9) IL_0000: newobj "Sub A..ctor()" IL_0005: stloc.0 IL_0006: newobj "Sub B..ctor()" IL_000b: stloc.1 IL_000c: ldsfld "C._Closure$__.$I1-0 As <generated method>" IL_0011: brfalse.s IL_001a IL_0013: ldsfld "C._Closure$__.$I1-0 As <generated method>" IL_0018: br.s IL_0030 IL_001a: ldsfld "C._Closure$__.$I As C._Closure$__" IL_001f: ldftn "Sub C._Closure$__._Lambda$__1-0()" IL_0025: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_002a: dup IL_002b: stsfld "C._Closure$__.$I1-0 As <generated method>" IL_0030: stloc.2 IL_0031: ldsfld "C._Closure$__.$I1-1 As <generated method>" IL_0036: brfalse.s IL_003f IL_0038: ldsfld "C._Closure$__.$I1-1 As <generated method>" IL_003d: br.s IL_0055 IL_003f: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0044: ldftn "Sub C._Closure$__._Lambda$__1-1(String)" IL_004a: newobj "Sub VB$AnonymousDelegate_1(Of String)..ctor(Object, System.IntPtr)" IL_004f: dup IL_0050: stsfld "C._Closure$__.$I1-1 As <generated method>" IL_0055: stloc.3 IL_0056: ldsfld "C._Closure$__.$I1-2 As <generated method>" IL_005b: brfalse.s IL_0064 IL_005d: ldsfld "C._Closure$__.$I1-2 As <generated method>" IL_0062: br.s IL_007a IL_0064: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0069: ldftn "Sub C._Closure$__._Lambda$__1-2(Object)" IL_006f: newobj "Sub VB$AnonymousDelegate_2(Of Object)..ctor(Object, System.IntPtr)" IL_0074: dup IL_0075: stsfld "C._Closure$__.$I1-2 As <generated method>" IL_007a: stloc.s V_4 IL_007c: ldsfld "C._Closure$__.$I1-3 As <generated method>" IL_0081: brfalse.s IL_008a IL_0083: ldsfld "C._Closure$__.$I1-3 As <generated method>" IL_0088: br.s IL_00a0 IL_008a: ldsfld "C._Closure$__.$I As C._Closure$__" IL_008f: ldftn "Sub C._Closure$__._Lambda$__1-3(EventLibrary.voidVoidDelegate)" IL_0095: newobj "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate)..ctor(Object, System.IntPtr)" IL_009a: dup IL_009b: stsfld "C._Closure$__.$I1-3 As <generated method>" IL_00a0: stloc.s V_5 IL_00a2: ldloc.0 IL_00a3: dup IL_00a4: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_00aa: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00af: ldloc.0 IL_00b0: dup IL_00b1: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_00b7: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00bc: ldloc.2 IL_00bd: stloc.s V_6 IL_00bf: ldloc.s V_6 IL_00c1: brfalse.s IL_00d2 IL_00c3: ldloc.s V_6 IL_00c5: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_00cb: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_00d0: br.s IL_00d3 IL_00d2: ldnull IL_00d3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_00d8: ldloc.0 IL_00d9: dup IL_00da: ldvirtftn "Sub A.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_00e0: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00e5: ldloc.0 IL_00e6: dup IL_00e7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_00ed: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00f2: ldloc.3 IL_00f3: stloc.s V_7 IL_00f5: ldloc.s V_7 IL_00f7: brfalse.s IL_0108 IL_00f9: ldloc.s V_7 IL_00fb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_0101: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_0106: br.s IL_0109 IL_0108: ldnull IL_0109: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_010e: ldloc.0 IL_010f: dup IL_0110: ldvirtftn "Sub A.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_0116: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_011b: ldloc.0 IL_011c: dup IL_011d: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0123: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0128: ldloc.s V_4 IL_012a: stloc.s V_8 IL_012c: ldloc.s V_8 IL_012e: brfalse.s IL_013f IL_0130: ldloc.s V_8 IL_0132: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_0138: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_013d: br.s IL_0140 IL_013f: ldnull IL_0140: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_0145: ldloc.0 IL_0146: dup IL_0147: ldvirtftn "Sub A.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_014d: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0152: ldloc.0 IL_0153: dup IL_0154: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_015a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_015f: ldloc.s V_5 IL_0161: stloc.s V_9 IL_0163: ldloc.s V_9 IL_0165: brfalse.s IL_0176 IL_0167: ldloc.s V_9 IL_0169: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_016f: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_0174: br.s IL_0177 IL_0176: ldnull IL_0177: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_017c: ldloc.0 IL_017d: dup IL_017e: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0184: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0189: ldloc.2 IL_018a: stloc.s V_6 IL_018c: ldloc.s V_6 IL_018e: brfalse.s IL_019f IL_0190: ldloc.s V_6 IL_0192: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0198: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_019d: br.s IL_01a0 IL_019f: ldnull IL_01a0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_01a5: ldloc.0 IL_01a6: dup IL_01a7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_01ad: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_01b2: ldloc.3 IL_01b3: stloc.s V_7 IL_01b5: ldloc.s V_7 IL_01b7: brfalse.s IL_01c8 IL_01b9: ldloc.s V_7 IL_01bb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_01c1: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_01c6: br.s IL_01c9 IL_01c8: ldnull IL_01c9: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_01ce: ldloc.0 IL_01cf: dup IL_01d0: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_01d6: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_01db: ldloc.s V_4 IL_01dd: stloc.s V_8 IL_01df: ldloc.s V_8 IL_01e1: brfalse.s IL_01f2 IL_01e3: ldloc.s V_8 IL_01e5: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_01eb: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_01f0: br.s IL_01f3 IL_01f2: ldnull IL_01f3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_01f8: ldloc.0 IL_01f9: dup IL_01fa: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0200: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0205: ldloc.s V_5 IL_0207: stloc.s V_9 IL_0209: ldloc.s V_9 IL_020b: brfalse.s IL_021c IL_020d: ldloc.s V_9 IL_020f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_0215: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_021a: br.s IL_021d IL_021c: ldnull IL_021d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_0222: ldloc.1 IL_0223: dup IL_0224: ldvirtftn "Sub B.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_022a: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_022f: ldloc.1 IL_0230: dup IL_0231: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0237: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_023c: ldloc.2 IL_023d: stloc.s V_6 IL_023f: ldloc.s V_6 IL_0241: brfalse.s IL_0252 IL_0243: ldloc.s V_6 IL_0245: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_024b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0250: br.s IL_0253 IL_0252: ldnull IL_0253: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0258: ldloc.1 IL_0259: dup IL_025a: ldvirtftn "Sub B.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_0260: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0265: ldloc.1 IL_0266: dup IL_0267: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_026d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0272: ldloc.3 IL_0273: stloc.s V_7 IL_0275: ldloc.s V_7 IL_0277: brfalse.s IL_0288 IL_0279: ldloc.s V_7 IL_027b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_0281: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_0286: br.s IL_0289 IL_0288: ldnull IL_0289: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_028e: ldloc.1 IL_028f: dup IL_0290: ldvirtftn "Sub B.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_0296: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_029b: ldloc.1 IL_029c: dup IL_029d: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_02a3: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_02a8: ldloc.s V_4 IL_02aa: stloc.s V_8 IL_02ac: ldloc.s V_8 IL_02ae: brfalse.s IL_02bf IL_02b0: ldloc.s V_8 IL_02b2: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_02b8: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_02bd: br.s IL_02c0 IL_02bf: ldnull IL_02c0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_02c5: ldloc.1 IL_02c6: dup IL_02c7: ldvirtftn "Sub B.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_02cd: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_02d2: ldloc.1 IL_02d3: dup IL_02d4: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_02da: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_02df: ldloc.s V_5 IL_02e1: stloc.s V_9 IL_02e3: ldloc.s V_9 IL_02e5: brfalse.s IL_02f6 IL_02e7: ldloc.s V_9 IL_02e9: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_02ef: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_02f4: br.s IL_02f7 IL_02f6: ldnull IL_02f7: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_02fc: ldloc.1 IL_02fd: dup IL_02fe: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0304: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0309: ldloc.2 IL_030a: stloc.s V_6 IL_030c: ldloc.s V_6 IL_030e: brfalse.s IL_031f IL_0310: ldloc.s V_6 IL_0312: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0318: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_031d: br.s IL_0320 IL_031f: ldnull IL_0320: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0325: ldloc.1 IL_0326: dup IL_0327: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_032d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0332: ldloc.3 IL_0333: stloc.s V_7 IL_0335: ldloc.s V_7 IL_0337: brfalse.s IL_0348 IL_0339: ldloc.s V_7 IL_033b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_0341: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_0346: br.s IL_0349 IL_0348: ldnull IL_0349: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_034e: ldloc.1 IL_034f: dup IL_0350: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0356: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_035b: ldloc.s V_4 IL_035d: stloc.s V_8 IL_035f: ldloc.s V_8 IL_0361: brfalse.s IL_0372 IL_0363: ldloc.s V_8 IL_0365: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_036b: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_0370: br.s IL_0373 IL_0372: ldnull IL_0373: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_0378: ldloc.1 IL_0379: dup IL_037a: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0380: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0385: ldloc.s V_5 IL_0387: stloc.s V_9 IL_0389: ldloc.s V_9 IL_038b: brfalse.s IL_039c IL_038d: ldloc.s V_9 IL_038f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_0395: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_039a: br.s IL_039d IL_039c: ldnull IL_039d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_03a2: ret } ]]>.Value) End Sub <Fact()> Public Sub WinMdEventInternalStaticAccess() Dim src = <compilation> <file name="a.vb"> <![CDATA[ Imports EventLibrary Public Partial Class A Implements I ' Remove a delegate from inside of the class Public Shared Function Scenario1(a As A) As Boolean Dim testDelegate = Sub() End Sub ' Setup AddHandler a.d1, testDelegate RemoveHandler a.d1, testDelegate Return a.d1Event Is Nothing End Function ' Remove a delegate from inside of the class Public Function Scenario2() As Boolean Dim b As A = Me Dim testDelegate = Sub() End Sub ' Setup AddHandler b.d1, testDelegate RemoveHandler b.d1, testDelegate Return b.d1Event Is Nothing End Function End Class ]]> </file> <file name="b.vb"> <%= _dynamicCommonSrc %> </file> </compilation> Dim verifier = CompileAndVerifyOnWin8Only( src, allReferences:={ MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929, _eventLibRef}) verifier.VerifyDiagnostics() verifier.VerifyIL("A.Scenario1", <![CDATA[ { // Code size 136 (0x88) .maxstack 4 .locals init (VB$AnonymousDelegate_0 V_0, //testDelegate VB$AnonymousDelegate_0 V_1) IL_0000: ldsfld "A._Closure$__.$I1-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "A._Closure$__.$I1-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "A._Closure$__.$I As A._Closure$__" IL_0013: ldftn "Sub A._Closure$__._Lambda$__1-0()" IL_0019: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "A._Closure$__.$I1-0 As <generated method>" IL_0024: stloc.0 IL_0025: ldarg.0 IL_0026: dup IL_0027: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_002d: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0032: ldarg.0 IL_0033: dup IL_0034: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_003a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_003f: ldloc.0 IL_0040: stloc.1 IL_0041: ldloc.1 IL_0042: brfalse.s IL_0052 IL_0044: ldloc.1 IL_0045: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_004b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0050: br.s IL_0053 IL_0052: ldnull IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0058: ldarg.0 IL_0059: dup IL_005a: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0060: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0065: ldloc.0 IL_0066: stloc.1 IL_0067: ldloc.1 IL_0068: brfalse.s IL_0078 IL_006a: ldloc.1 IL_006b: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0071: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0076: br.s IL_0079 IL_0078: ldnull IL_0079: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_007e: ldarg.0 IL_007f: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)" IL_0084: ldnull IL_0085: ceq IL_0087: ret } ]]>.Value) verifier.VerifyIL("A.Scenario2", <![CDATA[ { // Code size 138 (0x8a) .maxstack 4 .locals init (A V_0, //b VB$AnonymousDelegate_0 V_1, //testDelegate VB$AnonymousDelegate_0 V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldsfld "A._Closure$__.$I2-0 As <generated method>" IL_0007: brfalse.s IL_0010 IL_0009: ldsfld "A._Closure$__.$I2-0 As <generated method>" IL_000e: br.s IL_0026 IL_0010: ldsfld "A._Closure$__.$I As A._Closure$__" IL_0015: ldftn "Sub A._Closure$__._Lambda$__2-0()" IL_001b: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0020: dup IL_0021: stsfld "A._Closure$__.$I2-0 As <generated method>" IL_0026: stloc.1 IL_0027: ldloc.0 IL_0028: dup IL_0029: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_002f: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0034: ldloc.0 IL_0035: dup IL_0036: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0041: ldloc.1 IL_0042: stloc.2 IL_0043: ldloc.2 IL_0044: brfalse.s IL_0054 IL_0046: ldloc.2 IL_0047: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_004d: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0052: br.s IL_0055 IL_0054: ldnull IL_0055: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_005a: ldloc.0 IL_005b: dup IL_005c: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0062: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0067: ldloc.1 IL_0068: stloc.2 IL_0069: ldloc.2 IL_006a: brfalse.s IL_007a IL_006c: ldloc.2 IL_006d: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0073: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0078: br.s IL_007b IL_007a: ldnull IL_007b: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0080: ldloc.0 IL_0081: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)" IL_0086: ldnull IL_0087: ceq IL_0089: ret } ]]>.Value) End Sub ''' <summary> ''' Verify that WinRT events compile into the IL that we ''' would expect. ''' </summary> <ConditionalFact(GetType(OSVersionWin8))> <WorkItem(18092, "https://github.com/dotnet/roslyn/issues/18092")> Public Sub WinMdEvent() Dim source = <compilation> <file name="a.vb"> Imports System Imports Windows.ApplicationModel Imports Windows.UI.Xaml Public Class abcdef Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs) End Sub Public Sub goo() Dim application As Application = Nothing AddHandler application.Suspending, AddressOf Me.OnSuspending RemoveHandler application.Suspending, AddressOf Me.OnSuspending End Sub Public Shared Sub Main() Dim abcdef As abcdef = New abcdef() abcdef.goo() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithWinRt(source) Dim expectedIL = <output> { // Code size 76 (0x4c) .maxstack 4 .locals init (Windows.UI.Xaml.Application V_0) //application IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: dup IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_000f: ldloc.0 IL_0010: dup IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_001c: ldarg.0 IL_001d: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)" IL_0023: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)" IL_0028: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)" IL_002d: ldloc.0 IL_002e: dup IL_002f: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0035: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_003a: ldarg.0 IL_003b: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)" IL_0041: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)" IL_0046: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)" IL_004b: ret } </output> CompileAndVerify(compilation).VerifyIL("abcdef.goo", expectedIL.Value()) End Sub <Fact()> Public Sub WinMdSynthesizedEventDelegate() Dim src = <compilation> <file name="c.vb"> Class C Event E(a As Integer) End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences( src, references:={MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseWinMD) comp.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E")) End Sub ''' <summary> ''' Verify that WinRT events compile into the IL that we ''' would expect. ''' </summary> Public Sub WinMdEventLambda() Dim source = <compilation> <file name="a.vb"> Imports System Imports Windows.ApplicationModel Imports Windows.UI.Xaml Public Class abcdef Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs) End Sub Public Sub goo() Dim application As Application = Nothing AddHandler application.Suspending, Sub(sender as Object, e As SuspendingEventArgs) End Sub End Sub Public Shared Sub Main() Dim abcdef As abcdef = New abcdef() abcdef.goo() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithWinRt(source) Dim expectedIL = <output> { // Code size 66 (0x42) .maxstack 4 .locals init (Windows.UI.Xaml.Application V_0) //application IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: dup IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_000f: ldloc.0 IL_0010: dup IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_001c: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler" IL_0021: brfalse.s IL_002a IL_0023: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler" IL_0028: br.s IL_003c IL_002a: ldnull IL_002b: ldftn "Sub abcdef._Lambda$__1(Object, Object, Windows.ApplicationModel.SuspendingEventArgs)" IL_0031: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)" IL_0036: dup IL_0037: stsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler" IL_003c: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)" IL_0041: ret } </output> CompileAndVerify(compilation, verify:=If(OSVersion.IsWin8, Verification.Passes, Verification.Skipped)).VerifyIL("abcdef.goo", expectedIL.Value()) End Sub <Fact> Public Sub IsWindowsRuntimeEvent_EventSymbolSubtypes() Dim il = <![CDATA[ .class public auto ansi sealed Event extends [mscorlib]System.MulticastDelegate { .method private hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public hidebysig newslot specialname virtual instance void Invoke() runtime managed { } } // end of class Event .class interface public abstract auto ansi Interface`1<T> { .method public hidebysig newslot specialname abstract virtual instance void add_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_WinRT([in] class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed { } .event Event Normal { .addon instance void Interface`1::add_Normal(class Event) .removeon instance void Interface`1::remove_Normal(class Event) } // end of event I`1::Normal .event Event WinRT { .addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken Interface`1::add_WinRT(class Event) .removeon instance void Interface`1::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) } } // end of class Interface ]]> Dim source = <compilation> <file name="a.vb"> Class C Implements [Interface](Of Integer) Public Event Normal() Implements [Interface](Of Integer).Normal Public Event WinRT() Implements [Interface](Of Integer).WinRT End Class </file> </compilation> Dim ilRef = CompileIL(il.Value) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef})) comp.VerifyDiagnostics() Dim interfaceType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Interface") Dim interfaceNormalEvent = interfaceType.GetMember(Of EventSymbol)("Normal") Dim interfaceWinRTEvent = interfaceType.GetMember(Of EventSymbol)("WinRT") Assert.IsType(Of PEEventSymbol)(interfaceNormalEvent) Assert.IsType(Of PEEventSymbol)(interfaceWinRTEvent) ' Only depends on accessor signatures - doesn't care if it's in a windowsruntime type. Assert.False(interfaceNormalEvent.IsWindowsRuntimeEvent) Assert.True(interfaceWinRTEvent.IsWindowsRuntimeEvent) Dim implementingType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim implementingNormalEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal")) Dim implementingWinRTEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT")) Assert.IsType(Of SourceEventSymbol)(implementingNormalEvent) Assert.IsType(Of SourceEventSymbol)(implementingWinRTEvent) ' Based on kind of explicitly implemented interface event (other checks to be tested separately). Assert.False(implementingNormalEvent.IsWindowsRuntimeEvent) Assert.True(implementingWinRTEvent.IsWindowsRuntimeEvent) Dim substitutedNormalEvent = implementingNormalEvent.ExplicitInterfaceImplementations.Single() Dim substitutedWinRTEvent = implementingWinRTEvent.ExplicitInterfaceImplementations.Single() Assert.IsType(Of SubstitutedEventSymbol)(substitutedNormalEvent) Assert.IsType(Of SubstitutedEventSymbol)(substitutedWinRTEvent) ' Based on original definition. Assert.False(substitutedNormalEvent.IsWindowsRuntimeEvent) Assert.True(substitutedWinRTEvent.IsWindowsRuntimeEvent) Dim retargetingAssembly = New RetargetingAssemblySymbol(DirectCast(comp.Assembly, SourceAssemblySymbol), isLinked:=False) retargetingAssembly.SetCorLibrary(comp.Assembly.CorLibrary) Dim retargetingType = retargetingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim retargetingNormalEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal")) Dim retargetingWinRTEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT")) Assert.IsType(Of RetargetingEventSymbol)(retargetingNormalEvent) Assert.IsType(Of RetargetingEventSymbol)(retargetingWinRTEvent) ' Based on underlying symbol. Assert.False(retargetingNormalEvent.IsWindowsRuntimeEvent) Assert.True(retargetingWinRTEvent.IsWindowsRuntimeEvent) End Sub <Fact> Public Sub IsWindowsRuntimeEvent_Source_OutputKind() Dim source = <compilation> <file name="a.vb"> Class C Public Event E As System.Action Shared Sub Main() End Sub End Class Interface I Event E As System.Action End Interface </file> </compilation> For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind)) comp.VerifyDiagnostics() Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim classEvent = [class].GetMember(Of EventSymbol)("E") ' Specifically test interfaces because they follow a different code path. Dim [interface] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("I") Dim interfaceEvent = [interface].GetMember(Of EventSymbol)("E") Assert.Equal(kind.IsWindowsRuntime(), classEvent.IsWindowsRuntimeEvent) Assert.Equal(kind.IsWindowsRuntime(), interfaceEvent.IsWindowsRuntimeEvent) Next End Sub <Fact> Public Sub IsWindowsRuntimeEvent_Source_InterfaceImplementation() Dim source = <compilation> <file name="a.vb"> Class C Implements I Public Event Normal Implements I.Normal Public Event WinRT Implements I.WinRT Shared Sub Main() End Sub End Class </file> </compilation> Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I")) For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), New VisualBasicCompilationOptions(kind)) comp.VerifyDiagnostics() Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim normalEvent = [class].GetMember(Of EventSymbol)("Normal") Dim winRTEvent = [class].GetMember(Of EventSymbol)("WinRT") Assert.False(normalEvent.IsWindowsRuntimeEvent) Assert.True(winRTEvent.IsWindowsRuntimeEvent) Next End Sub <Fact> Public Sub ERR_MixingWinRTAndNETEvents() Dim source = <compilation> <file name="a.vb"> ' Fine to implement more than one interface of the same WinRT-ness Class C1 Implements I1, I2 Public Event Normal Implements I1.Normal, I2.Normal Public Event WinRT Implements I1.WinRT, I2.WinRT End Class ' Error to implement two interfaces of different WinRT-ness Class C2 Implements I1, I2 Public Event Normal Implements I1.Normal, I2.WinRT Public Event WinRT Implements I1.WinRT, I2.Normal End Class </file> </compilation> Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2")) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal"), Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.Normal").WithArguments("WinRT", "I1.WinRT", "I2.Normal")) Dim c1 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C1") Assert.False(c1.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent) Assert.True(c1.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent) Dim c2 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C2") Assert.False(c2.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent) Assert.True(c2.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_MixingWinRTAndNETEvents_Multiple() Dim source = <compilation> <file name="a.vb"> ' Try going back and forth Class C3 Implements I1, I2 Public Event Normal Implements I1.Normal, I1.WinRT, I2.Normal, I2.WinRT End Class </file> </compilation> Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2")) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll) ' CONSIDER: This is not how dev11 handles this scenario: it reports the first diagnostic, but then reports ' ERR_IdentNotMemberOfInterface4 (BC30401) and ERR_UnimplementedMember3 (BC30149) for all subsequent implemented members ' (side-effects of calling SetIsBad on the implementing event). comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I1.WinRT").WithArguments("Normal", "I1.WinRT", "I1.Normal"), Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal")) Dim c3 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C3") Assert.False(c3.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_WinRTEventWithoutDelegate_FieldLike() Dim source = <compilation> <file name="a.vb"> Class Test Public Event E ' As System.Action End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)> Public Sub ERR_WinRTEventWithoutDelegate_Custom() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E ' As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' Once the as-clause is missing, the event is parsed as a field-like event, hence the many syntax errors. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"), Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E ' As System.Action" + Environment.NewLine), Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"), Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"), Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"), Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"), Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_WinRTEventWithoutDelegate_Implements() Dim source = <compilation> <file name="a.vb"> Interface I Event E1 As System.Action Event E2 As System.Action End Interface Class Test Implements I Public Event E1 Implements I.E1 Public Custom Event E2 Implements I.E2 AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' Everything goes sideways for E2 since it custom events are required to have as-clauses. ' The key thing is that neither event reports ERR_WinRTEventWithoutDelegate. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E2 Implements I.E2"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"), Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"), Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"), Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"), Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event"), Diagnostic(ERRID.ERR_EventImplMismatch5, "I.E2").WithArguments("Public Event E2 As ?", "Event E2 As System.Action", "I", "?", "System.Action")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E1").IsWindowsRuntimeEvent) Assert.True(type.GetMember(Of EventSymbol)("E2").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_AddParamWrongForWinRT() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action(Of Integer)) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_AddParamWrongForWinRT, "AddHandler(value As System.Action(Of Integer))")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_RemoveParamWrongForWinRT() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_RemoveParamWrongForWinRT, "RemoveHandler(value As System.Action)")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_RemoveParamWrongForWinRT_MissingTokenType() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD) ' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type ' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action) Return Nothing End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", comp.AssemblyName + ".winmdobj")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_EventImplRemoveHandlerParamWrong() Dim source = <compilation> <file name="a.vb"> Interface I Event E As System.Action end Interface Class Test Implements I Public Custom Event F As System.Action Implements I.E AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_EventImplRemoveHandlerParamWrong, "RemoveHandler(value As System.Action)").WithArguments("F", "E", "I")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_EventImplRemoveHandlerParamWrong_MissingTokenType() Dim source = <compilation> <file name="a.vb"> Interface I Event E As System.Action end Interface Class Test Implements I Public Custom Event F As System.Action Implements I.E AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD) ' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type ' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported. Dim outputName As String = comp.AssemblyName + ".winmdobj" comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action) Return Nothing End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName), Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName), Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName)) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent) End Sub ' Confirms that we're getting decl errors from the backing field. <Fact> Public Sub MissingTokenTableType() Dim source = <compilation name="test"> <file name="a.vb"> Class Test Event E As System.Action End Class Namespace System.Runtime.InteropServices.WindowsRuntime Public Structure EventRegistrationToken End Structure End Namespace </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD) AssertTheseDeclarationDiagnostics(comp, <errors><![CDATA[ BC31091: Import of type 'EventRegistrationTokenTable(Of )' from assembly or module 'test.winmdobj' failed. Event E As System.Action ~ ]]></errors>) End Sub <Fact> Public Sub ReturnLocal() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action) add_E = Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) Dim v = CompileAndVerify(comp) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim eventSymbol As EventSymbol = type.GetMember(Of EventSymbol)("E") Assert.True(eventSymbol.IsWindowsRuntimeEvent) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of AssignmentStatementSyntax).Single().Left Dim symbol = model.GetSymbolInfo(syntax).Symbol Assert.Equal(SymbolKind.Local, symbol.Kind) Assert.Equal(eventSymbol.AddMethod.ReturnType, DirectCast(symbol, LocalSymbol).Type) Assert.Equal(eventSymbol.AddMethod.Name, symbol.Name) v.VerifyIL("Test.add_E", " { // Code size 10 (0xa) .maxstack 1 .locals init (System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken V_0) //add_E IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"" IL_0008: ldloc.0 IL_0009: ret } ") End Sub <Fact> Public Sub AccessorSignatures() Dim source = <compilation> <file name="a.vb"> Class Test public event FieldLike As System.Action Public Custom Event Custom As System.Action AddHandler(value As System.Action) Throw New System.Exception() End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event Public Shared Sub Main() End Sub End Class </file> </compilation> For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind)) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim fieldLikeEvent = type.GetMember(Of EventSymbol)("FieldLike") Dim customEvent = type.GetMember(Of EventSymbol)("Custom") If kind.IsWindowsRuntime() Then comp.VerifyDiagnostics() VerifyWinRTEventShape(customEvent, comp) VerifyWinRTEventShape(fieldLikeEvent, comp) Else comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_AddRemoveParamNotEventType, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)")) VerifyNormalEventShape(customEvent, comp) VerifyNormalEventShape(fieldLikeEvent, comp) End If Next End Sub <Fact()> Public Sub HandlerSemanticInfo() Dim source = <compilation> <file name="a.vb"> Class C Event QQQ As System.Action Sub Test() AddHandler QQQ, Nothing RemoveHandler QQQ, Nothing RaiseEvent QQQ() End Sub End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD) comp.VerifyDiagnostics() Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim references = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText = "QQQ").ToArray() Assert.Equal(3, references.Count) ' Decl is just a token Dim eventSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of EventSymbol)("QQQ") AssertEx.All(references, Function(ref) model.GetSymbolInfo(ref).Symbol.Equals(eventSymbol)) Dim actionType = comp.GetWellKnownType(WellKnownType.System_Action) Assert.Equal(actionType, eventSymbol.Type) AssertEx.All(references, Function(ref) model.GetTypeInfo(ref).Type.Equals(actionType)) End Sub <Fact> Public Sub NoReturnFromAddHandler() Dim source = <compilation> <file name="a.vb"> Delegate Sub EventDelegate() Class Events Custom Event E As eventdelegate AddHandler(value As eventdelegate) End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' Note the distinct new error code. comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgNoRetValWinRtEventVal1, "End AddHandler").WithArguments("E")) End Sub Private Shared Sub VerifyWinRTEventShape([event] As EventSymbol, compilation As VisualBasicCompilation) Assert.True([event].IsWindowsRuntimeEvent) Dim eventType = [event].Type Dim tokenType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken) Assert.NotNull(tokenType) Dim voidType = compilation.GetSpecialType(SpecialType.System_Void) Assert.NotNull(voidType) Dim addMethod = [event].AddMethod Assert.Equal(tokenType, addMethod.ReturnType) Assert.False(addMethod.IsSub) Assert.Equal(1, addMethod.ParameterCount) Assert.Equal(eventType, addMethod.Parameters.Single().Type) Dim removeMethod = [event].RemoveMethod Assert.Equal(voidType, removeMethod.ReturnType) Assert.True(removeMethod.IsSub) Assert.Equal(1, removeMethod.ParameterCount) Assert.Equal(tokenType, removeMethod.Parameters.Single().Type) If [event].HasAssociatedField Then Dim expectedFieldType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T).Construct(eventType) Assert.Equal(expectedFieldType, [event].AssociatedField.Type) Else Assert.Null([event].AssociatedField) End If End Sub Private Shared Sub VerifyNormalEventShape([event] As EventSymbol, compilation As VisualBasicCompilation) Assert.False([event].IsWindowsRuntimeEvent) Dim eventType = [event].Type Dim voidType = compilation.GetSpecialType(SpecialType.System_Void) Assert.NotNull(voidType) Dim addMethod = [event].AddMethod Assert.Equal(voidType, addMethod.ReturnType) Assert.True(addMethod.IsSub) Assert.Equal(1, addMethod.ParameterCount) Assert.Equal(eventType, addMethod.Parameters.Single().Type) Dim removeMethod = [event].RemoveMethod Assert.Equal(voidType, removeMethod.ReturnType) Assert.True(removeMethod.IsSub) Assert.Equal(1, removeMethod.ParameterCount) If [event].HasAssociatedField Then ' Otherwise, we had to be explicit and we favored WinRT because that's what we're testing. Assert.Equal(eventType, removeMethod.Parameters.Single().Type) End If If [event].HasAssociatedField Then Assert.Equal(eventType, [event].AssociatedField.Type) Else Assert.Null([event].AssociatedField) End If End Sub <Fact> Public Sub BackingField() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event CustomEvent As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event Public Event FieldLikeEvent As System.Action Sub Test() dim f1 = CustomEventEvent dim f2 = FieldLikeEventEvent End Sub End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' No backing field for custom event. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_NameNotDeclared1, "CustomEventEvent").WithArguments("CustomEventEvent")) Dim fieldLikeEvent = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test").GetMember(Of EventSymbol)("FieldLikeEvent") Dim tokenTableType = comp.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Single(Function(id) id.Identifier.ValueText = "FieldLikeEventEvent") Dim symbol = model.GetSymbolInfo(syntax).Symbol Assert.Equal(SymbolKind.Field, symbol.Kind) Assert.Equal(fieldLikeEvent, DirectCast(symbol, FieldSymbol).AssociatedSymbol) Dim type = model.GetTypeInfo(syntax).Type Assert.Equal(tokenTableType, type.OriginalDefinition) Assert.Equal(fieldLikeEvent.Type, DirectCast(type, NamedTypeSymbol).TypeArguments.Single()) End Sub <Fact()> Public Sub RaiseBaseEventedFromDerivedNestedTypes() Dim source = <compilation> <file name="filename.vb"> Delegate Sub D() Class C1 Event HelloWorld As D Class C2 Inherits C1 Sub t RaiseEvent HelloWorld End Sub End Class End Class </file> </compilation> CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD).VerifyDiagnostics() End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Linq Imports System.Xml.Linq Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Metadata.PE Imports Microsoft.CodeAnalysis.VisualBasic.Symbols.Retargeting Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Symbols.Metadata Public Class WinMdEventTest Inherits BasicTestBase Private ReadOnly _eventInterfaceILTemplate As String = <![CDATA[ .class interface public abstract auto ansi {0} {{ .method public hidebysig newslot specialname abstract virtual instance void add_Normal(class [mscorlib]System.Action 'value') cil managed {{ }} .method public hidebysig newslot specialname abstract virtual instance void remove_Normal(class [mscorlib]System.Action 'value') cil managed {{ }} .method public hidebysig newslot specialname abstract virtual instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_WinRT([in] class [mscorlib]System.Action 'value') cil managed {{ }} .method public hidebysig newslot specialname abstract virtual instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed {{ }} .event class [mscorlib]System.Action Normal {{ .addon instance void {0}::add_Normal(class [mscorlib]System.Action) .removeon instance void {0}::remove_Normal(class [mscorlib]System.Action) }} .event class [mscorlib]System.Action WinRT {{ .addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken {0}::add_WinRT(class [mscorlib]System.Action) .removeon instance void {0}::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) }} }} // end of class {0} ]]>.Value Private ReadOnly _eventLibRef As MetadataReference Private ReadOnly _dynamicCommonSrc As XElement = <compilation> <file name="dynamic_common.vb"> <![CDATA[ Imports System.Runtime.InteropServices.WindowsRuntime Imports EventLibrary Public Partial Class A Implements I Public Event d1 As voidVoidDelegate Implements I.d1 Public Event d2 As voidStringDelegate Implements I.d2 Public Event d3 As voidDynamicDelegate Implements I.d3 Public Event d4 As voidDelegateDelegate Implements I.d4 End Class Public Partial Class B Implements I Private voidTable As New EventRegistrationTokenTable(Of voidVoidDelegate)() Private voidStringTable As New EventRegistrationTokenTable(Of voidStringDelegate)() Private voidDynamicTable As New EventRegistrationTokenTable(Of voidDynamicDelegate)() Private voidDelegateTable As New EventRegistrationTokenTable(Of voidDelegateDelegate)() Public Custom Event d1 As voidVoidDelegate Implements I.d1 AddHandler(value As voidVoidDelegate) Return voidTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent() End RaiseEvent End Event Public Custom Event d2 As voidStringDelegate Implements I.d2 AddHandler(value As voidStringDelegate) Return voidStringTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidStringTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent(s As String) End RaiseEvent End Event Public Custom Event d3 As voidDynamicDelegate Implements I.d3 AddHandler(value As voidDynamicDelegate) Return voidDynamicTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidDynamicTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent(d As Object) End RaiseEvent End Event Public Custom Event d4 As voidDelegateDelegate Implements I.d4 AddHandler(value As voidDelegateDelegate) Return voidDelegateTable.AddEventHandler(value) End AddHandler RemoveHandler(value As EventRegistrationToken) voidDelegateTable.RemoveEventHandler(value) End RemoveHandler RaiseEvent([delegate] As voidVoidDelegate) End RaiseEvent End Event End Class ]]> </file> </compilation> Public Sub New() ' The following two libraries are shrunk code pulled from ' corresponding files in the csharp5 legacy tests Dim eventLibSrc = <compilation><file name="EventLibrary.vb"> <![CDATA[ Namespace EventLibrary Public Delegate Sub voidVoidDelegate() Public Delegate Sub voidStringDelegate(s As String) Public Delegate Sub voidDynamicDelegate(d As Object) Public Delegate Sub voidDelegateDelegate([delegate] As voidVoidDelegate) Public Interface I Event d1 As voidVoidDelegate Event d2 As voidStringDelegate Event d3 As voidDynamicDelegate Event d4 As voidDelegateDelegate End Interface End Namespace ]]> </file></compilation> _eventLibRef = CreateEmptyCompilationWithReferences( eventLibSrc, references:={MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929}, options:=TestOptions.ReleaseWinMD).EmitToImageReference() End Sub <Fact()> Public Sub WinMdExternalEventTests() Dim src = <compilation><file name="c.vb"> <![CDATA[ Imports EventLibrary Class C Sub Main() Dim a = new A() Dim b = new B() Dim void = Sub() End Sub Dim str = Sub(s As String) End Sub Dim dyn = Sub(d As Object) End Sub Dim del = Sub([delegate] As voidVoidDelegate) End Sub AddHandler a.d1, void AddHandler a.d2, str AddHandler a.d3, dyn AddHandler a.d4, del RemoveHandler a.d1, void RemoveHandler a.d2, str RemoveHandler a.d3, dyn RemoveHandler a.d4, del AddHandler b.d1, void AddHandler b.d2, str AddHandler b.d3, dyn AddHandler b.d4, del RemoveHandler b.d1, void RemoveHandler b.d2, str RemoveHandler b.d3, dyn RemoveHandler b.d4, del End Sub End Class ]]> </file></compilation> Dim dynamicCommonRef As MetadataReference = CreateEmptyCompilationWithReferences( _dynamicCommonSrc, references:={ MscorlibRef_v4_0_30316_17626, _eventLibRef}, options:=TestOptions.ReleaseModule).EmitToImageReference() Dim verifier = CompileAndVerifyOnWin8Only( src, allReferences:={ MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929, CSharpRef, _eventLibRef, dynamicCommonRef}) verifier.VerifyIL("C.Main", <![CDATA[ { // Code size 931 (0x3a3) .maxstack 4 .locals init (A V_0, //a B V_1, //b VB$AnonymousDelegate_0 V_2, //void VB$AnonymousDelegate_1(Of String) V_3, //str VB$AnonymousDelegate_2(Of Object) V_4, //dyn VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_5, //del VB$AnonymousDelegate_0 V_6, VB$AnonymousDelegate_1(Of String) V_7, VB$AnonymousDelegate_2(Of Object) V_8, VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate) V_9) IL_0000: newobj "Sub A..ctor()" IL_0005: stloc.0 IL_0006: newobj "Sub B..ctor()" IL_000b: stloc.1 IL_000c: ldsfld "C._Closure$__.$I1-0 As <generated method>" IL_0011: brfalse.s IL_001a IL_0013: ldsfld "C._Closure$__.$I1-0 As <generated method>" IL_0018: br.s IL_0030 IL_001a: ldsfld "C._Closure$__.$I As C._Closure$__" IL_001f: ldftn "Sub C._Closure$__._Lambda$__1-0()" IL_0025: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_002a: dup IL_002b: stsfld "C._Closure$__.$I1-0 As <generated method>" IL_0030: stloc.2 IL_0031: ldsfld "C._Closure$__.$I1-1 As <generated method>" IL_0036: brfalse.s IL_003f IL_0038: ldsfld "C._Closure$__.$I1-1 As <generated method>" IL_003d: br.s IL_0055 IL_003f: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0044: ldftn "Sub C._Closure$__._Lambda$__1-1(String)" IL_004a: newobj "Sub VB$AnonymousDelegate_1(Of String)..ctor(Object, System.IntPtr)" IL_004f: dup IL_0050: stsfld "C._Closure$__.$I1-1 As <generated method>" IL_0055: stloc.3 IL_0056: ldsfld "C._Closure$__.$I1-2 As <generated method>" IL_005b: brfalse.s IL_0064 IL_005d: ldsfld "C._Closure$__.$I1-2 As <generated method>" IL_0062: br.s IL_007a IL_0064: ldsfld "C._Closure$__.$I As C._Closure$__" IL_0069: ldftn "Sub C._Closure$__._Lambda$__1-2(Object)" IL_006f: newobj "Sub VB$AnonymousDelegate_2(Of Object)..ctor(Object, System.IntPtr)" IL_0074: dup IL_0075: stsfld "C._Closure$__.$I1-2 As <generated method>" IL_007a: stloc.s V_4 IL_007c: ldsfld "C._Closure$__.$I1-3 As <generated method>" IL_0081: brfalse.s IL_008a IL_0083: ldsfld "C._Closure$__.$I1-3 As <generated method>" IL_0088: br.s IL_00a0 IL_008a: ldsfld "C._Closure$__.$I As C._Closure$__" IL_008f: ldftn "Sub C._Closure$__._Lambda$__1-3(EventLibrary.voidVoidDelegate)" IL_0095: newobj "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate)..ctor(Object, System.IntPtr)" IL_009a: dup IL_009b: stsfld "C._Closure$__.$I1-3 As <generated method>" IL_00a0: stloc.s V_5 IL_00a2: ldloc.0 IL_00a3: dup IL_00a4: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_00aa: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00af: ldloc.0 IL_00b0: dup IL_00b1: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_00b7: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00bc: ldloc.2 IL_00bd: stloc.s V_6 IL_00bf: ldloc.s V_6 IL_00c1: brfalse.s IL_00d2 IL_00c3: ldloc.s V_6 IL_00c5: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_00cb: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_00d0: br.s IL_00d3 IL_00d2: ldnull IL_00d3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_00d8: ldloc.0 IL_00d9: dup IL_00da: ldvirtftn "Sub A.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_00e0: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00e5: ldloc.0 IL_00e6: dup IL_00e7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_00ed: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_00f2: ldloc.3 IL_00f3: stloc.s V_7 IL_00f5: ldloc.s V_7 IL_00f7: brfalse.s IL_0108 IL_00f9: ldloc.s V_7 IL_00fb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_0101: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_0106: br.s IL_0109 IL_0108: ldnull IL_0109: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_010e: ldloc.0 IL_010f: dup IL_0110: ldvirtftn "Sub A.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_0116: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_011b: ldloc.0 IL_011c: dup IL_011d: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0123: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0128: ldloc.s V_4 IL_012a: stloc.s V_8 IL_012c: ldloc.s V_8 IL_012e: brfalse.s IL_013f IL_0130: ldloc.s V_8 IL_0132: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_0138: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_013d: br.s IL_0140 IL_013f: ldnull IL_0140: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_0145: ldloc.0 IL_0146: dup IL_0147: ldvirtftn "Sub A.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_014d: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0152: ldloc.0 IL_0153: dup IL_0154: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_015a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_015f: ldloc.s V_5 IL_0161: stloc.s V_9 IL_0163: ldloc.s V_9 IL_0165: brfalse.s IL_0176 IL_0167: ldloc.s V_9 IL_0169: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_016f: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_0174: br.s IL_0177 IL_0176: ldnull IL_0177: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_017c: ldloc.0 IL_017d: dup IL_017e: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0184: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0189: ldloc.2 IL_018a: stloc.s V_6 IL_018c: ldloc.s V_6 IL_018e: brfalse.s IL_019f IL_0190: ldloc.s V_6 IL_0192: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0198: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_019d: br.s IL_01a0 IL_019f: ldnull IL_01a0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_01a5: ldloc.0 IL_01a6: dup IL_01a7: ldvirtftn "Sub A.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_01ad: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_01b2: ldloc.3 IL_01b3: stloc.s V_7 IL_01b5: ldloc.s V_7 IL_01b7: brfalse.s IL_01c8 IL_01b9: ldloc.s V_7 IL_01bb: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_01c1: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_01c6: br.s IL_01c9 IL_01c8: ldnull IL_01c9: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_01ce: ldloc.0 IL_01cf: dup IL_01d0: ldvirtftn "Sub A.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_01d6: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_01db: ldloc.s V_4 IL_01dd: stloc.s V_8 IL_01df: ldloc.s V_8 IL_01e1: brfalse.s IL_01f2 IL_01e3: ldloc.s V_8 IL_01e5: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_01eb: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_01f0: br.s IL_01f3 IL_01f2: ldnull IL_01f3: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_01f8: ldloc.0 IL_01f9: dup IL_01fa: ldvirtftn "Sub A.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0200: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0205: ldloc.s V_5 IL_0207: stloc.s V_9 IL_0209: ldloc.s V_9 IL_020b: brfalse.s IL_021c IL_020d: ldloc.s V_9 IL_020f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_0215: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_021a: br.s IL_021d IL_021c: ldnull IL_021d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_0222: ldloc.1 IL_0223: dup IL_0224: ldvirtftn "Sub B.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_022a: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_022f: ldloc.1 IL_0230: dup IL_0231: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0237: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_023c: ldloc.2 IL_023d: stloc.s V_6 IL_023f: ldloc.s V_6 IL_0241: brfalse.s IL_0252 IL_0243: ldloc.s V_6 IL_0245: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_024b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0250: br.s IL_0253 IL_0252: ldnull IL_0253: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0258: ldloc.1 IL_0259: dup IL_025a: ldvirtftn "Sub B.add_d2(EventLibrary.voidStringDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_0260: newobj "Sub System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0265: ldloc.1 IL_0266: dup IL_0267: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_026d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0272: ldloc.3 IL_0273: stloc.s V_7 IL_0275: ldloc.s V_7 IL_0277: brfalse.s IL_0288 IL_0279: ldloc.s V_7 IL_027b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_0281: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_0286: br.s IL_0289 IL_0288: ldnull IL_0289: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidStringDelegate)(System.Func(Of EventLibrary.voidStringDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_028e: ldloc.1 IL_028f: dup IL_0290: ldvirtftn "Sub B.add_d3(EventLibrary.voidDynamicDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_0296: newobj "Sub System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_029b: ldloc.1 IL_029c: dup IL_029d: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_02a3: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_02a8: ldloc.s V_4 IL_02aa: stloc.s V_8 IL_02ac: ldloc.s V_8 IL_02ae: brfalse.s IL_02bf IL_02b0: ldloc.s V_8 IL_02b2: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_02b8: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_02bd: br.s IL_02c0 IL_02bf: ldnull IL_02c0: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Func(Of EventLibrary.voidDynamicDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_02c5: ldloc.1 IL_02c6: dup IL_02c7: ldvirtftn "Sub B.add_d4(EventLibrary.voidDelegateDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_02cd: newobj "Sub System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_02d2: ldloc.1 IL_02d3: dup IL_02d4: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_02da: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_02df: ldloc.s V_5 IL_02e1: stloc.s V_9 IL_02e3: ldloc.s V_9 IL_02e5: brfalse.s IL_02f6 IL_02e7: ldloc.s V_9 IL_02e9: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_02ef: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_02f4: br.s IL_02f7 IL_02f6: ldnull IL_02f7: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Func(Of EventLibrary.voidDelegateDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_02fc: ldloc.1 IL_02fd: dup IL_02fe: ldvirtftn "Sub B.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0304: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0309: ldloc.2 IL_030a: stloc.s V_6 IL_030c: ldloc.s V_6 IL_030e: brfalse.s IL_031f IL_0310: ldloc.s V_6 IL_0312: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0318: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_031d: br.s IL_0320 IL_031f: ldnull IL_0320: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0325: ldloc.1 IL_0326: dup IL_0327: ldvirtftn "Sub B.remove_d2(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_032d: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0332: ldloc.3 IL_0333: stloc.s V_7 IL_0335: ldloc.s V_7 IL_0337: brfalse.s IL_0348 IL_0339: ldloc.s V_7 IL_033b: ldftn "Sub VB$AnonymousDelegate_1(Of String).Invoke(String)" IL_0341: newobj "Sub EventLibrary.voidStringDelegate..ctor(Object, System.IntPtr)" IL_0346: br.s IL_0349 IL_0348: ldnull IL_0349: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidStringDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidStringDelegate)" IL_034e: ldloc.1 IL_034f: dup IL_0350: ldvirtftn "Sub B.remove_d3(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0356: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_035b: ldloc.s V_4 IL_035d: stloc.s V_8 IL_035f: ldloc.s V_8 IL_0361: brfalse.s IL_0372 IL_0363: ldloc.s V_8 IL_0365: ldftn "Sub VB$AnonymousDelegate_2(Of Object).Invoke(Object)" IL_036b: newobj "Sub EventLibrary.voidDynamicDelegate..ctor(Object, System.IntPtr)" IL_0370: br.s IL_0373 IL_0372: ldnull IL_0373: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDynamicDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDynamicDelegate)" IL_0378: ldloc.1 IL_0379: dup IL_037a: ldvirtftn "Sub B.remove_d4(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0380: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0385: ldloc.s V_5 IL_0387: stloc.s V_9 IL_0389: ldloc.s V_9 IL_038b: brfalse.s IL_039c IL_038d: ldloc.s V_9 IL_038f: ldftn "Sub VB$AnonymousDelegate_3(Of EventLibrary.voidVoidDelegate).Invoke(EventLibrary.voidVoidDelegate)" IL_0395: newobj "Sub EventLibrary.voidDelegateDelegate..ctor(Object, System.IntPtr)" IL_039a: br.s IL_039d IL_039c: ldnull IL_039d: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidDelegateDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidDelegateDelegate)" IL_03a2: ret } ]]>.Value) End Sub <Fact()> Public Sub WinMdEventInternalStaticAccess() Dim src = <compilation> <file name="a.vb"> <![CDATA[ Imports EventLibrary Public Partial Class A Implements I ' Remove a delegate from inside of the class Public Shared Function Scenario1(a As A) As Boolean Dim testDelegate = Sub() End Sub ' Setup AddHandler a.d1, testDelegate RemoveHandler a.d1, testDelegate Return a.d1Event Is Nothing End Function ' Remove a delegate from inside of the class Public Function Scenario2() As Boolean Dim b As A = Me Dim testDelegate = Sub() End Sub ' Setup AddHandler b.d1, testDelegate RemoveHandler b.d1, testDelegate Return b.d1Event Is Nothing End Function End Class ]]> </file> <file name="b.vb"> <%= _dynamicCommonSrc %> </file> </compilation> Dim verifier = CompileAndVerifyOnWin8Only( src, allReferences:={ MscorlibRef_v4_0_30316_17626, SystemCoreRef_v4_0_30319_17929, _eventLibRef}) verifier.VerifyDiagnostics() verifier.VerifyIL("A.Scenario1", <![CDATA[ { // Code size 136 (0x88) .maxstack 4 .locals init (VB$AnonymousDelegate_0 V_0, //testDelegate VB$AnonymousDelegate_0 V_1) IL_0000: ldsfld "A._Closure$__.$I1-0 As <generated method>" IL_0005: brfalse.s IL_000e IL_0007: ldsfld "A._Closure$__.$I1-0 As <generated method>" IL_000c: br.s IL_0024 IL_000e: ldsfld "A._Closure$__.$I As A._Closure$__" IL_0013: ldftn "Sub A._Closure$__._Lambda$__1-0()" IL_0019: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_001e: dup IL_001f: stsfld "A._Closure$__.$I1-0 As <generated method>" IL_0024: stloc.0 IL_0025: ldarg.0 IL_0026: dup IL_0027: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_002d: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0032: ldarg.0 IL_0033: dup IL_0034: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_003a: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_003f: ldloc.0 IL_0040: stloc.1 IL_0041: ldloc.1 IL_0042: brfalse.s IL_0052 IL_0044: ldloc.1 IL_0045: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_004b: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0050: br.s IL_0053 IL_0052: ldnull IL_0053: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0058: ldarg.0 IL_0059: dup IL_005a: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0060: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0065: ldloc.0 IL_0066: stloc.1 IL_0067: ldloc.1 IL_0068: brfalse.s IL_0078 IL_006a: ldloc.1 IL_006b: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0071: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0076: br.s IL_0079 IL_0078: ldnull IL_0079: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_007e: ldarg.0 IL_007f: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)" IL_0084: ldnull IL_0085: ceq IL_0087: ret } ]]>.Value) verifier.VerifyIL("A.Scenario2", <![CDATA[ { // Code size 138 (0x8a) .maxstack 4 .locals init (A V_0, //b VB$AnonymousDelegate_0 V_1, //testDelegate VB$AnonymousDelegate_0 V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldsfld "A._Closure$__.$I2-0 As <generated method>" IL_0007: brfalse.s IL_0010 IL_0009: ldsfld "A._Closure$__.$I2-0 As <generated method>" IL_000e: br.s IL_0026 IL_0010: ldsfld "A._Closure$__.$I As A._Closure$__" IL_0015: ldftn "Sub A._Closure$__._Lambda$__2-0()" IL_001b: newobj "Sub VB$AnonymousDelegate_0..ctor(Object, System.IntPtr)" IL_0020: dup IL_0021: stsfld "A._Closure$__.$I2-0 As <generated method>" IL_0026: stloc.1 IL_0027: ldloc.0 IL_0028: dup IL_0029: ldvirtftn "Sub A.add_d1(EventLibrary.voidVoidDelegate) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_002f: newobj "Sub System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0034: ldloc.0 IL_0035: dup IL_0036: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_003c: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0041: ldloc.1 IL_0042: stloc.2 IL_0043: ldloc.2 IL_0044: brfalse.s IL_0054 IL_0046: ldloc.2 IL_0047: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_004d: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0052: br.s IL_0055 IL_0054: ldnull IL_0055: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of EventLibrary.voidVoidDelegate)(System.Func(Of EventLibrary.voidVoidDelegate, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_005a: ldloc.0 IL_005b: dup IL_005c: ldvirtftn "Sub A.remove_d1(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0062: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_0067: ldloc.1 IL_0068: stloc.2 IL_0069: ldloc.2 IL_006a: brfalse.s IL_007a IL_006c: ldloc.2 IL_006d: ldftn "Sub VB$AnonymousDelegate_0.Invoke()" IL_0073: newobj "Sub EventLibrary.voidVoidDelegate..ctor(Object, System.IntPtr)" IL_0078: br.s IL_007b IL_007a: ldnull IL_007b: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of EventLibrary.voidVoidDelegate)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), EventLibrary.voidVoidDelegate)" IL_0080: ldloc.0 IL_0081: ldfld "A.d1Event As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable(Of EventLibrary.voidVoidDelegate)" IL_0086: ldnull IL_0087: ceq IL_0089: ret } ]]>.Value) End Sub ''' <summary> ''' Verify that WinRT events compile into the IL that we ''' would expect. ''' </summary> <ConditionalFact(GetType(OSVersionWin8))> <WorkItem(18092, "https://github.com/dotnet/roslyn/issues/18092")> Public Sub WinMdEvent() Dim source = <compilation> <file name="a.vb"> Imports System Imports Windows.ApplicationModel Imports Windows.UI.Xaml Public Class abcdef Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs) End Sub Public Sub goo() Dim application As Application = Nothing AddHandler application.Suspending, AddressOf Me.OnSuspending RemoveHandler application.Suspending, AddressOf Me.OnSuspending End Sub Public Shared Sub Main() Dim abcdef As abcdef = New abcdef() abcdef.goo() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithWinRt(source) Dim expectedIL = <output> { // Code size 76 (0x4c) .maxstack 4 .locals init (Windows.UI.Xaml.Application V_0) //application IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: dup IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_000f: ldloc.0 IL_0010: dup IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_001c: ldarg.0 IL_001d: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)" IL_0023: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)" IL_0028: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)" IL_002d: ldloc.0 IL_002e: dup IL_002f: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0035: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_003a: ldarg.0 IL_003b: ldftn "Sub abcdef.OnSuspending(Object, Windows.ApplicationModel.SuspendingEventArgs)" IL_0041: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)" IL_0046: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.RemoveEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)" IL_004b: ret } </output> CompileAndVerify(compilation).VerifyIL("abcdef.goo", expectedIL.Value()) End Sub <Fact()> Public Sub WinMdSynthesizedEventDelegate() Dim src = <compilation> <file name="c.vb"> Class C Event E(a As Integer) End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences( src, references:={MscorlibRef_v4_0_30316_17626}, options:=TestOptions.ReleaseWinMD) comp.VerifyEmitDiagnostics(Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E")) End Sub ''' <summary> ''' Verify that WinRT events compile into the IL that we ''' would expect. ''' </summary> Public Sub WinMdEventLambda() Dim source = <compilation> <file name="a.vb"> Imports System Imports Windows.ApplicationModel Imports Windows.UI.Xaml Public Class abcdef Private Sub OnSuspending(sender As Object, e As SuspendingEventArgs) End Sub Public Sub goo() Dim application As Application = Nothing AddHandler application.Suspending, Sub(sender as Object, e As SuspendingEventArgs) End Sub End Sub Public Shared Sub Main() Dim abcdef As abcdef = New abcdef() abcdef.goo() End Sub End Class </file> </compilation> Dim compilation = CreateCompilationWithWinRt(source) Dim expectedIL = <output> { // Code size 66 (0x42) .maxstack 4 .locals init (Windows.UI.Xaml.Application V_0) //application IL_0000: ldnull IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: dup IL_0004: ldvirtftn "Sub Windows.UI.Xaml.Application.add_Suspending(Windows.UI.Xaml.SuspendingEventHandler) As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken" IL_000a: newobj "Sub System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_000f: ldloc.0 IL_0010: dup IL_0011: ldvirtftn "Sub Windows.UI.Xaml.Application.remove_Suspending(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)" IL_0017: newobj "Sub System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)..ctor(Object, System.IntPtr)" IL_001c: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler" IL_0021: brfalse.s IL_002a IL_0023: ldsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler" IL_0028: br.s IL_003c IL_002a: ldnull IL_002b: ldftn "Sub abcdef._Lambda$__1(Object, Object, Windows.ApplicationModel.SuspendingEventArgs)" IL_0031: newobj "Sub Windows.UI.Xaml.SuspendingEventHandler..ctor(Object, System.IntPtr)" IL_0036: dup IL_0037: stsfld "abcdef._ClosureCache$__2 As Windows.UI.Xaml.SuspendingEventHandler" IL_003c: call "Sub System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeMarshal.AddEventHandler(Of Windows.UI.Xaml.SuspendingEventHandler)(System.Func(Of Windows.UI.Xaml.SuspendingEventHandler, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), System.Action(Of System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken), Windows.UI.Xaml.SuspendingEventHandler)" IL_0041: ret } </output> CompileAndVerify(compilation, verify:=If(OSVersion.IsWin8, Verification.Passes, Verification.Skipped)).VerifyIL("abcdef.goo", expectedIL.Value()) End Sub <Fact> Public Sub IsWindowsRuntimeEvent_EventSymbolSubtypes() Dim il = <![CDATA[ .class public auto ansi sealed Event extends [mscorlib]System.MulticastDelegate { .method private hidebysig specialname rtspecialname instance void .ctor(object 'object', native int 'method') runtime managed { } .method public hidebysig newslot specialname virtual instance void Invoke() runtime managed { } } // end of class Event .class interface public abstract auto ansi Interface`1<T> { .method public hidebysig newslot specialname abstract virtual instance void add_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_Normal(class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken add_WinRT([in] class Event 'value') cil managed { } .method public hidebysig newslot specialname abstract virtual instance void remove_WinRT([in] valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken 'value') cil managed { } .event Event Normal { .addon instance void Interface`1::add_Normal(class Event) .removeon instance void Interface`1::remove_Normal(class Event) } // end of event I`1::Normal .event Event WinRT { .addon instance valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken Interface`1::add_WinRT(class Event) .removeon instance void Interface`1::remove_WinRT(valuetype [mscorlib]System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) } } // end of class Interface ]]> Dim source = <compilation> <file name="a.vb"> Class C Implements [Interface](Of Integer) Public Event Normal() Implements [Interface](Of Integer).Normal Public Event WinRT() Implements [Interface](Of Integer).WinRT End Class </file> </compilation> Dim ilRef = CompileIL(il.Value) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef})) comp.VerifyDiagnostics() Dim interfaceType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Interface") Dim interfaceNormalEvent = interfaceType.GetMember(Of EventSymbol)("Normal") Dim interfaceWinRTEvent = interfaceType.GetMember(Of EventSymbol)("WinRT") Assert.IsType(Of PEEventSymbol)(interfaceNormalEvent) Assert.IsType(Of PEEventSymbol)(interfaceWinRTEvent) ' Only depends on accessor signatures - doesn't care if it's in a windowsruntime type. Assert.False(interfaceNormalEvent.IsWindowsRuntimeEvent) Assert.True(interfaceWinRTEvent.IsWindowsRuntimeEvent) Dim implementingType = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim implementingNormalEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal")) Dim implementingWinRTEvent = implementingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT")) Assert.IsType(Of SourceEventSymbol)(implementingNormalEvent) Assert.IsType(Of SourceEventSymbol)(implementingWinRTEvent) ' Based on kind of explicitly implemented interface event (other checks to be tested separately). Assert.False(implementingNormalEvent.IsWindowsRuntimeEvent) Assert.True(implementingWinRTEvent.IsWindowsRuntimeEvent) Dim substitutedNormalEvent = implementingNormalEvent.ExplicitInterfaceImplementations.Single() Dim substitutedWinRTEvent = implementingWinRTEvent.ExplicitInterfaceImplementations.Single() Assert.IsType(Of SubstitutedEventSymbol)(substitutedNormalEvent) Assert.IsType(Of SubstitutedEventSymbol)(substitutedWinRTEvent) ' Based on original definition. Assert.False(substitutedNormalEvent.IsWindowsRuntimeEvent) Assert.True(substitutedWinRTEvent.IsWindowsRuntimeEvent) Dim retargetingAssembly = New RetargetingAssemblySymbol(DirectCast(comp.Assembly, SourceAssemblySymbol), isLinked:=False) retargetingAssembly.SetCorLibrary(comp.Assembly.CorLibrary) Dim retargetingType = retargetingAssembly.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim retargetingNormalEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("Normal")) Dim retargetingWinRTEvent = retargetingType.GetMembers().OfType(Of EventSymbol)().Single(Function(e) e.Name.Contains("WinRT")) Assert.IsType(Of RetargetingEventSymbol)(retargetingNormalEvent) Assert.IsType(Of RetargetingEventSymbol)(retargetingWinRTEvent) ' Based on underlying symbol. Assert.False(retargetingNormalEvent.IsWindowsRuntimeEvent) Assert.True(retargetingWinRTEvent.IsWindowsRuntimeEvent) End Sub <Fact> Public Sub IsWindowsRuntimeEvent_Source_OutputKind() Dim source = <compilation> <file name="a.vb"> Class C Public Event E As System.Action Shared Sub Main() End Sub End Class Interface I Event E As System.Action End Interface </file> </compilation> For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind)) comp.VerifyDiagnostics() Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim classEvent = [class].GetMember(Of EventSymbol)("E") ' Specifically test interfaces because they follow a different code path. Dim [interface] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("I") Dim interfaceEvent = [interface].GetMember(Of EventSymbol)("E") Assert.Equal(kind.IsWindowsRuntime(), classEvent.IsWindowsRuntimeEvent) Assert.Equal(kind.IsWindowsRuntime(), interfaceEvent.IsWindowsRuntimeEvent) Next End Sub <Fact> Public Sub IsWindowsRuntimeEvent_Source_InterfaceImplementation() Dim source = <compilation> <file name="a.vb"> Class C Implements I Public Event Normal Implements I.Normal Public Event WinRT Implements I.WinRT Shared Sub Main() End Sub End Class </file> </compilation> Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I")) For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), New VisualBasicCompilationOptions(kind)) comp.VerifyDiagnostics() Dim [class] = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C") Dim normalEvent = [class].GetMember(Of EventSymbol)("Normal") Dim winRTEvent = [class].GetMember(Of EventSymbol)("WinRT") Assert.False(normalEvent.IsWindowsRuntimeEvent) Assert.True(winRTEvent.IsWindowsRuntimeEvent) Next End Sub <Fact> Public Sub ERR_MixingWinRTAndNETEvents() Dim source = <compilation> <file name="a.vb"> ' Fine to implement more than one interface of the same WinRT-ness Class C1 Implements I1, I2 Public Event Normal Implements I1.Normal, I2.Normal Public Event WinRT Implements I1.WinRT, I2.WinRT End Class ' Error to implement two interfaces of different WinRT-ness Class C2 Implements I1, I2 Public Event Normal Implements I1.Normal, I2.WinRT Public Event WinRT Implements I1.WinRT, I2.Normal End Class </file> </compilation> Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2")) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal"), Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.Normal").WithArguments("WinRT", "I1.WinRT", "I2.Normal")) Dim c1 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C1") Assert.False(c1.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent) Assert.True(c1.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent) Dim c2 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C2") Assert.False(c2.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent) Assert.True(c2.GetMember(Of EventSymbol)("WinRT").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_MixingWinRTAndNETEvents_Multiple() Dim source = <compilation> <file name="a.vb"> ' Try going back and forth Class C3 Implements I1, I2 Public Event Normal Implements I1.Normal, I1.WinRT, I2.Normal, I2.WinRT End Class </file> </compilation> Dim ilRef = CompileIL(String.Format(_eventInterfaceILTemplate, "I1") + String.Format(_eventInterfaceILTemplate, "I2")) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs.Concat({ilRef}), TestOptions.ReleaseDll) ' CONSIDER: This is not how dev11 handles this scenario: it reports the first diagnostic, but then reports ' ERR_IdentNotMemberOfInterface4 (BC30401) and ERR_UnimplementedMember3 (BC30149) for all subsequent implemented members ' (side-effects of calling SetIsBad on the implementing event). comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I1.WinRT").WithArguments("Normal", "I1.WinRT", "I1.Normal"), Diagnostic(ERRID.ERR_MixingWinRTAndNETEvents, "I2.WinRT").WithArguments("Normal", "I2.WinRT", "I1.Normal")) Dim c3 = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C3") Assert.False(c3.GetMember(Of EventSymbol)("Normal").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_WinRTEventWithoutDelegate_FieldLike() Dim source = <compilation> <file name="a.vb"> Class Test Public Event E ' As System.Action End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <ConditionalFact(GetType(WindowsOnly), Reason:=ConditionalSkipReason.TestExecutionNeedsWindowsTypes)> Public Sub ERR_WinRTEventWithoutDelegate_Custom() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E ' As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' Once the as-clause is missing, the event is parsed as a field-like event, hence the many syntax errors. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_WinRTEventWithoutDelegate, "E"), Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E ' As System.Action" + Environment.NewLine), Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"), Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"), Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"), Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"), Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_WinRTEventWithoutDelegate_Implements() Dim source = <compilation> <file name="a.vb"> Interface I Event E1 As System.Action Event E2 As System.Action End Interface Class Test Implements I Public Event E1 Implements I.E1 Public Custom Event E2 Implements I.E2 AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' Everything goes sideways for E2 since it custom events are required to have as-clauses. ' The key thing is that neither event reports ERR_WinRTEventWithoutDelegate. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_CustomEventRequiresAs, "Public Custom Event E2 Implements I.E2"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "AddHandler(value As System.Action)"), Diagnostic(ERRID.ERR_ExecutableAsDeclaration, "Return Nothing"), Diagnostic(ERRID.ERR_InvalidEndAddHandler, "End AddHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)"), Diagnostic(ERRID.ERR_InvalidEndRemoveHandler, "End RemoveHandler"), Diagnostic(ERRID.ERR_ExpectedDeclaration, "RaiseEvent()"), Diagnostic(ERRID.ERR_InvalidEndRaiseEvent, "End RaiseEvent"), Diagnostic(ERRID.ERR_InvalidEndEvent, "End Event"), Diagnostic(ERRID.ERR_EventImplMismatch5, "I.E2").WithArguments("Public Event E2 As ?", "Event E2 As System.Action", "I", "?", "System.Action")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E1").IsWindowsRuntimeEvent) Assert.True(type.GetMember(Of EventSymbol)("E2").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_AddParamWrongForWinRT() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action(Of Integer)) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_AddParamWrongForWinRT, "AddHandler(value As System.Action(Of Integer))")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_RemoveParamWrongForWinRT() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_RemoveParamWrongForWinRT, "RemoveHandler(value As System.Action)")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_RemoveParamWrongForWinRT_MissingTokenType() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD) ' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type ' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action) Return Nothing End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", comp.AssemblyName + ".winmdobj")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("E").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_EventImplRemoveHandlerParamWrong() Dim source = <compilation> <file name="a.vb"> Interface I Event E As System.Action end Interface Class Test Implements I Public Custom Event F As System.Action Implements I.E AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_EventImplRemoveHandlerParamWrong, "RemoveHandler(value As System.Action)").WithArguments("F", "E", "I")) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent) End Sub <Fact> Public Sub ERR_EventImplRemoveHandlerParamWrong_MissingTokenType() Dim source = <compilation> <file name="a.vb"> Interface I Event E As System.Action end Interface Class Test Implements I Public Custom Event F As System.Action Implements I.E AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Action) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD) ' This diagnostic is from binding the return type of the AddHandler, not from checking the parameter type ' of the ReturnHandler. The key point is that a cascading ERR_RemoveParamWrongForWinRT is not reported. Dim outputName As String = comp.AssemblyName + ".winmdobj" comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_TypeRefResolutionError3, <![CDATA[AddHandler(value As System.Action) Return Nothing End AddHandler]]>.Value.Replace(vbLf, vbCrLf)).WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName), Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName), Diagnostic(ERRID.ERR_TypeRefResolutionError3, "E").WithArguments("System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken", outputName)) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Assert.True(type.GetMember(Of EventSymbol)("F").IsWindowsRuntimeEvent) End Sub ' Confirms that we're getting decl errors from the backing field. <Fact> Public Sub MissingTokenTableType() Dim source = <compilation name="test"> <file name="a.vb"> Class Test Event E As System.Action End Class Namespace System.Runtime.InteropServices.WindowsRuntime Public Structure EventRegistrationToken End Structure End Namespace </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, {TestMetadata.Net40.mscorlib}, TestOptions.ReleaseWinMD) AssertTheseDeclarationDiagnostics(comp, <errors><![CDATA[ BC31091: Import of type 'EventRegistrationTokenTable(Of )' from assembly or module 'test.winmdobj' failed. Event E As System.Action ~ ]]></errors>) End Sub <Fact> Public Sub ReturnLocal() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event E As System.Action AddHandler(value As System.Action) add_E = Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) Dim v = CompileAndVerify(comp) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim eventSymbol As EventSymbol = type.GetMember(Of EventSymbol)("E") Assert.True(eventSymbol.IsWindowsRuntimeEvent) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of AssignmentStatementSyntax).Single().Left Dim symbol = model.GetSymbolInfo(syntax).Symbol Assert.Equal(SymbolKind.Local, symbol.Kind) Assert.Equal(eventSymbol.AddMethod.ReturnType, DirectCast(symbol, LocalSymbol).Type) Assert.Equal(eventSymbol.AddMethod.Name, symbol.Name) v.VerifyIL("Test.add_E", " { // Code size 10 (0xa) .maxstack 1 .locals init (System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken V_0) //add_E IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken"" IL_0008: ldloc.0 IL_0009: ret } ") End Sub <Fact> Public Sub AccessorSignatures() Dim source = <compilation> <file name="a.vb"> Class Test public event FieldLike As System.Action Public Custom Event Custom As System.Action AddHandler(value As System.Action) Throw New System.Exception() End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event Public Shared Sub Main() End Sub End Class </file> </compilation> For Each kind As OutputKind In [Enum].GetValues(GetType(OutputKind)) Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, New VisualBasicCompilationOptions(kind)) Dim type = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test") Dim fieldLikeEvent = type.GetMember(Of EventSymbol)("FieldLike") Dim customEvent = type.GetMember(Of EventSymbol)("Custom") If kind.IsWindowsRuntime() Then comp.VerifyDiagnostics() VerifyWinRTEventShape(customEvent, comp) VerifyWinRTEventShape(fieldLikeEvent, comp) Else comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_AddRemoveParamNotEventType, "RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken)")) VerifyNormalEventShape(customEvent, comp) VerifyNormalEventShape(fieldLikeEvent, comp) End If Next End Sub <Fact()> Public Sub HandlerSemanticInfo() Dim source = <compilation> <file name="a.vb"> Class C Event QQQ As System.Action Sub Test() AddHandler QQQ, Nothing RemoveHandler QQQ, Nothing RaiseEvent QQQ() End Sub End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, options:=TestOptions.ReleaseWinMD) comp.VerifyDiagnostics() Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim references = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax).Where(Function(id) id.Identifier.ValueText = "QQQ").ToArray() Assert.Equal(3, references.Count) ' Decl is just a token Dim eventSymbol = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("C").GetMember(Of EventSymbol)("QQQ") AssertEx.All(references, Function(ref) model.GetSymbolInfo(ref).Symbol.Equals(eventSymbol)) Dim actionType = comp.GetWellKnownType(WellKnownType.System_Action) Assert.Equal(actionType, eventSymbol.Type) AssertEx.All(references, Function(ref) model.GetTypeInfo(ref).Type.Equals(actionType)) End Sub <Fact> Public Sub NoReturnFromAddHandler() Dim source = <compilation> <file name="a.vb"> Delegate Sub EventDelegate() Class Events Custom Event E As eventdelegate AddHandler(value As eventdelegate) End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' Note the distinct new error code. comp.VerifyDiagnostics( Diagnostic(ERRID.WRN_DefAsgNoRetValWinRtEventVal1, "End AddHandler").WithArguments("E")) End Sub Private Shared Sub VerifyWinRTEventShape([event] As EventSymbol, compilation As VisualBasicCompilation) Assert.True([event].IsWindowsRuntimeEvent) Dim eventType = [event].Type Dim tokenType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationToken) Assert.NotNull(tokenType) Dim voidType = compilation.GetSpecialType(SpecialType.System_Void) Assert.NotNull(voidType) Dim addMethod = [event].AddMethod Assert.Equal(tokenType, addMethod.ReturnType) Assert.False(addMethod.IsSub) Assert.Equal(1, addMethod.ParameterCount) Assert.Equal(eventType, addMethod.Parameters.Single().Type) Dim removeMethod = [event].RemoveMethod Assert.Equal(voidType, removeMethod.ReturnType) Assert.True(removeMethod.IsSub) Assert.Equal(1, removeMethod.ParameterCount) Assert.Equal(tokenType, removeMethod.Parameters.Single().Type) If [event].HasAssociatedField Then Dim expectedFieldType = compilation.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T).Construct(eventType) Assert.Equal(expectedFieldType, [event].AssociatedField.Type) Else Assert.Null([event].AssociatedField) End If End Sub Private Shared Sub VerifyNormalEventShape([event] As EventSymbol, compilation As VisualBasicCompilation) Assert.False([event].IsWindowsRuntimeEvent) Dim eventType = [event].Type Dim voidType = compilation.GetSpecialType(SpecialType.System_Void) Assert.NotNull(voidType) Dim addMethod = [event].AddMethod Assert.Equal(voidType, addMethod.ReturnType) Assert.True(addMethod.IsSub) Assert.Equal(1, addMethod.ParameterCount) Assert.Equal(eventType, addMethod.Parameters.Single().Type) Dim removeMethod = [event].RemoveMethod Assert.Equal(voidType, removeMethod.ReturnType) Assert.True(removeMethod.IsSub) Assert.Equal(1, removeMethod.ParameterCount) If [event].HasAssociatedField Then ' Otherwise, we had to be explicit and we favored WinRT because that's what we're testing. Assert.Equal(eventType, removeMethod.Parameters.Single().Type) End If If [event].HasAssociatedField Then Assert.Equal(eventType, [event].AssociatedField.Type) Else Assert.Null([event].AssociatedField) End If End Sub <Fact> Public Sub BackingField() Dim source = <compilation> <file name="a.vb"> Class Test Public Custom Event CustomEvent As System.Action AddHandler(value As System.Action) Return Nothing End AddHandler RemoveHandler(value As System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken) End RemoveHandler RaiseEvent() End RaiseEvent End Event Public Event FieldLikeEvent As System.Action Sub Test() dim f1 = CustomEventEvent dim f2 = FieldLikeEventEvent End Sub End Class </file> </compilation> Dim comp = CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD) ' No backing field for custom event. comp.VerifyDiagnostics( Diagnostic(ERRID.ERR_NameNotDeclared1, "CustomEventEvent").WithArguments("CustomEventEvent")) Dim fieldLikeEvent = comp.GlobalNamespace.GetMember(Of NamedTypeSymbol)("Test").GetMember(Of EventSymbol)("FieldLikeEvent") Dim tokenTableType = comp.GetWellKnownType(WellKnownType.System_Runtime_InteropServices_WindowsRuntime_EventRegistrationTokenTable_T) Dim tree = comp.SyntaxTrees.Single() Dim model = comp.GetSemanticModel(tree) Dim syntax = tree.GetRoot().DescendantNodes().OfType(Of IdentifierNameSyntax)().Single(Function(id) id.Identifier.ValueText = "FieldLikeEventEvent") Dim symbol = model.GetSymbolInfo(syntax).Symbol Assert.Equal(SymbolKind.Field, symbol.Kind) Assert.Equal(fieldLikeEvent, DirectCast(symbol, FieldSymbol).AssociatedSymbol) Dim type = model.GetTypeInfo(syntax).Type Assert.Equal(tokenTableType, type.OriginalDefinition) Assert.Equal(fieldLikeEvent.Type, DirectCast(type, NamedTypeSymbol).TypeArguments.Single()) End Sub <Fact()> Public Sub RaiseBaseEventedFromDerivedNestedTypes() Dim source = <compilation> <file name="filename.vb"> Delegate Sub D() Class C1 Event HelloWorld As D Class C2 Inherits C1 Sub t RaiseEvent HelloWorld End Sub End Class End Class </file> </compilation> CreateEmptyCompilationWithReferences(source, WinRtRefs, TestOptions.ReleaseWinMD).VerifyDiagnostics() End Sub End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Portable/BoundTree/BoundNullCoalescingOperatorResultKind.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Represents the operand type used for the result of a null-coalescing /// operator. Used when determining nullability. /// </summary> internal enum BoundNullCoalescingOperatorResultKind { /// <summary> /// No valid type for operator. /// </summary> NoCommonType, /// <summary> /// Type of left operand is used. /// </summary> LeftType, /// <summary> /// Nullable underlying type of left operand is used. /// </summary> LeftUnwrappedType, /// <summary> /// Type of right operand is used. /// </summary> RightType, /// <summary> /// Type of right operand is used and nullable left operand is converted /// to underlying type before converting to right operand type. /// </summary> LeftUnwrappedRightType, /// <summary> /// Type of right operand is dynamic and is used. /// </summary> RightDynamicType, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// Represents the operand type used for the result of a null-coalescing /// operator. Used when determining nullability. /// </summary> internal enum BoundNullCoalescingOperatorResultKind { /// <summary> /// No valid type for operator. /// </summary> NoCommonType, /// <summary> /// Type of left operand is used. /// </summary> LeftType, /// <summary> /// Nullable underlying type of left operand is used. /// </summary> LeftUnwrappedType, /// <summary> /// Type of right operand is used. /// </summary> RightType, /// <summary> /// Type of right operand is used and nullable left operand is converted /// to underlying type before converting to right operand type. /// </summary> LeftUnwrappedRightType, /// <summary> /// Type of right operand is dynamic and is used. /// </summary> RightDynamicType, } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Test/Semantic/Semantics/MemberResolutionResultTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics { public class MemberResolutionResultTests { [Fact] public void Equality() { var d = default(MemberResolutionResult<MethodSymbol>); Assert.Throws<NotSupportedException>(() => d.Equals(d)); Assert.Throws<NotSupportedException>(() => d.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. #nullable disable using Microsoft.CodeAnalysis.CSharp.Symbols; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.Semantics { public class MemberResolutionResultTests { [Fact] public void Equality() { var d = default(MemberResolutionResult<MethodSymbol>); Assert.Throws<NotSupportedException>(() => d.Equals(d)); Assert.Throws<NotSupportedException>(() => d.GetHashCode()); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/Core/Portable/Diagnostic/MetadataLocation.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 Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A program location in metadata. /// </summary> internal sealed class MetadataLocation : Location, IEquatable<MetadataLocation?> { private readonly IModuleSymbolInternal _module; internal MetadataLocation(IModuleSymbolInternal module) { RoslynDebug.Assert(module != null); _module = module; } public override LocationKind Kind { get { return LocationKind.MetadataFile; } } internal override IModuleSymbolInternal MetadataModuleInternal { get { return _module; } } public override int GetHashCode() { return _module.GetHashCode(); } public override bool Equals(object? obj) { return Equals(obj as MetadataLocation); } public bool Equals(MetadataLocation? other) { return other is object && other._module == _module; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// A program location in metadata. /// </summary> internal sealed class MetadataLocation : Location, IEquatable<MetadataLocation?> { private readonly IModuleSymbolInternal _module; internal MetadataLocation(IModuleSymbolInternal module) { RoslynDebug.Assert(module != null); _module = module; } public override LocationKind Kind { get { return LocationKind.MetadataFile; } } internal override IModuleSymbolInternal MetadataModuleInternal { get { return _module; } } public override int GetHashCode() { return _module.GetHashCode(); } public override bool Equals(object? obj) { return Equals(obj as MetadataLocation); } public bool Equals(MetadataLocation? other) { return other is object && other._module == _module; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Services/Precedence/IPrecedenceService.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.Precedence { internal interface IPrecedenceService { /// <summary> /// Returns the precedence of the given expression, mapped down to one of the /// <see cref="PrecedenceKind"/> values. The mapping is language specific. /// </summary> PrecedenceKind GetPrecedenceKind(int operatorPrecedence); /// <summary> /// Returns the precedence of this expression in a scale specific to a particular /// language. These values cannot be compared across languages, but relates the /// precedence of expressions in the same language. A smaller value means lower /// precedence. /// </summary> int GetOperatorPrecedence(SyntaxNode expression); } internal abstract class AbstractPrecedenceService< TExpressionSyntax, TOperatorPrecedence> : IPrecedenceService where TExpressionSyntax : SyntaxNode where TOperatorPrecedence : struct { int IPrecedenceService.GetOperatorPrecedence(SyntaxNode expression) => (int)(object)this.GetOperatorPrecedence((TExpressionSyntax)expression); PrecedenceKind IPrecedenceService.GetPrecedenceKind(int operatorPrecedence) => this.GetPrecedenceKind((TOperatorPrecedence)(object)operatorPrecedence); public abstract TOperatorPrecedence GetOperatorPrecedence(TExpressionSyntax expression); public abstract PrecedenceKind GetPrecedenceKind(TOperatorPrecedence operatorPrecedence); } internal static class PrecedenceServiceExtensions { public static PrecedenceKind GetPrecedenceKind(this IPrecedenceService service, SyntaxNode expression) => service.GetPrecedenceKind(service.GetOperatorPrecedence(expression)); } }
// Licensed to the .NET Foundation under one or more agreements. // The .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.Precedence { internal interface IPrecedenceService { /// <summary> /// Returns the precedence of the given expression, mapped down to one of the /// <see cref="PrecedenceKind"/> values. The mapping is language specific. /// </summary> PrecedenceKind GetPrecedenceKind(int operatorPrecedence); /// <summary> /// Returns the precedence of this expression in a scale specific to a particular /// language. These values cannot be compared across languages, but relates the /// precedence of expressions in the same language. A smaller value means lower /// precedence. /// </summary> int GetOperatorPrecedence(SyntaxNode expression); } internal abstract class AbstractPrecedenceService< TExpressionSyntax, TOperatorPrecedence> : IPrecedenceService where TExpressionSyntax : SyntaxNode where TOperatorPrecedence : struct { int IPrecedenceService.GetOperatorPrecedence(SyntaxNode expression) => (int)(object)this.GetOperatorPrecedence((TExpressionSyntax)expression); PrecedenceKind IPrecedenceService.GetPrecedenceKind(int operatorPrecedence) => this.GetPrecedenceKind((TOperatorPrecedence)(object)operatorPrecedence); public abstract TOperatorPrecedence GetOperatorPrecedence(TExpressionSyntax expression); public abstract PrecedenceKind GetPrecedenceKind(TOperatorPrecedence operatorPrecedence); } internal static class PrecedenceServiceExtensions { public static PrecedenceKind GetPrecedenceKind(this IPrecedenceService service, SyntaxNode expression) => service.GetPrecedenceKind(service.GetOperatorPrecedence(expression)); } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/CSharpTest/Structure/MetadataAsSource/RegionDirectiveStructureTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStructureTests<RegionDirectiveTriviaSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task FileHeader() { const string code = @" {|span:#re$$gion Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll #endregion|}"; await VerifyBlockSpansAsync(code, Region("span", "Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task EmptyFileHeader() { const string code = @" {|span:#re$$gion // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll #endregion|}"; await VerifyBlockSpansAsync(code, Region("span", "#region", autoCollapse: 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.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Structure; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Structure.MetadataAsSource { public class RegionDirectiveStructureTests : AbstractCSharpSyntaxNodeStructureTests<RegionDirectiveTriviaSyntax> { protected override string WorkspaceKind => CodeAnalysis.WorkspaceKind.MetadataAsSource; internal override AbstractSyntaxStructureProvider CreateProvider() => new RegionDirectiveStructureProvider(); [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task FileHeader() { const string code = @" {|span:#re$$gion Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll #endregion|}"; await VerifyBlockSpansAsync(code, Region("span", "Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", autoCollapse: true)); } [Fact, Trait(Traits.Feature, Traits.Features.MetadataAsSource)] public async Task EmptyFileHeader() { const string code = @" {|span:#re$$gion // C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll #endregion|}"; await VerifyBlockSpansAsync(code, Region("span", "#region", autoCollapse: true)); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/Core/Portable/CodeRefactorings/SyncNamespace/AbstractSyncNamespaceCodeRefactoringProvider.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace { internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> : CodeRefactoringProvider where TNamespaceDeclarationSyntax : SyntaxNode where TCompilationUnitSyntax : SyntaxNode where TMemberDeclarationSyntax : SyntaxNode { internal sealed class State { /// <summary> /// The document in which the refactoring is triggered. /// </summary> public Document Document { get; } /// <summary> /// The applicable container node based on cursor location, /// which will be used to change namespace. /// </summary> public SyntaxNode Container { get; } /// <summary> /// This is the new name we want to change the namespace to. /// Empty string means global namespace, whereas null means change namespace action is not available. /// </summary> public string TargetNamespace { get; } /// <summary> /// This is the part of the declared namespace that is contained in default namespace. /// We will use this to construct target folder to move the file to. /// For example, if default namespace is `A` and declared namespace is `A.B.C`, /// this would be `B.C`. /// </summary> public string RelativeDeclaredNamespace { get; } private State( Document document, SyntaxNode container, string targetNamespace, string relativeDeclaredNamespace) { Document = document; Container = container; TargetNamespace = targetNamespace; RelativeDeclaredNamespace = relativeDeclaredNamespace; } public static async Task<State> CreateAsync( AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> provider, Document document, TextSpan textSpan, CancellationToken cancellationToken) { // User must put cursor on one of the nodes described below to trigger the refactoring. // For each scenario, all requirements must be met. Some of them are checked by `TryGetApplicableInvocationNodeAsync`, // rest by `IChangeNamespaceService.CanChangeNamespaceAsync`. // // - A namespace declaration node that is the only namespace declaration in the document and all types are declared in it: // 1. No nested namespace declarations (even it's empty). // 2. The cursor is on the name of the namespace declaration. // 3. The name of the namespace is valid (i.e. no errors). // 4. No partial type declared in the namespace. Otherwise its multiple declaration will // end up in different namespace. // // - A compilation unit node that contains no namespace declaration: // 1. The cursor is on the name of first declared type. // 2. No partial type declared in the document. Otherwise its multiple declaration will // end up in different namespace. var applicableNode = await provider.TryGetApplicableInvocationNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (applicableNode == null) { return null; } var changeNamespaceService = document.GetLanguageService<IChangeNamespaceService>(); var canChange = await changeNamespaceService.CanChangeNamespaceAsync(document, applicableNode, cancellationToken).ConfigureAwait(false); if (!canChange || !IsDocumentPathRootedInProjectFolder(document)) { return null; } var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); // We can't determine what the expected namespace would be without knowing the default namespace. var defaultNamespace = GetDefaultNamespace(document, syntaxFacts); if (defaultNamespace == null) { return null; } string declaredNamespace; if (applicableNode is TCompilationUnitSyntax) { declaredNamespace = string.Empty; } else if (applicableNode is TNamespaceDeclarationSyntax) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); declaredNamespace = syntaxGenerator.GetName(applicableNode); } else { throw ExceptionUtilities.Unreachable; } // Namespace can't be changed if we can't construct a valid qualified identifier from folder names. // In this case, we might still be able to provide refactoring to move file to new location. var targetNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(document.Folders, syntaxFacts, defaultNamespace); // No action required if namespace already matches folders. if (syntaxFacts.StringComparer.Equals(targetNamespace, declaredNamespace)) { return null; } // Only provide "move file" action if default namespace contains declared namespace. // For example, if the default namespace is `Microsoft.CodeAnalysis`, and declared // namespace is `System.Diagnostics`, it's very likely this document is an outlier // in the project and user probably has some special rule for it. var relativeNamespace = GetRelativeNamespace(defaultNamespace, declaredNamespace, syntaxFacts); return new State(document, applicableNode, targetNamespace, relativeNamespace); } /// <summary> /// Determines if the actual file path matches its logical path in project /// which is constructed as [project_root_path]\Logical\Folders\. The refactoring /// is triggered only when the two match. The reason of doing this is we don't really know /// the user's intention of keeping the file path out-of-sync with its logical path. /// </summary> private static bool IsDocumentPathRootedInProjectFolder(Document document) { var projectRoot = PathUtilities.GetDirectoryName(document.Project.FilePath); var folderPath = Path.Combine(document.Folders.ToArray()); var absoluteDircetoryPath = PathUtilities.GetDirectoryName(document.FilePath); var logicalDirectoryPath = PathUtilities.CombineAbsoluteAndRelativePaths(projectRoot, folderPath); return PathUtilities.PathsEqual(absoluteDircetoryPath, logicalDirectoryPath); } private static string GetDefaultNamespace(Document document, ISyntaxFactsService syntaxFacts) { var solution = document.Project.Solution; var linkedIds = document.GetLinkedDocumentIds(); var documents = linkedIds.SelectAsArray(id => solution.GetDocument(id)).Add(document); // For all projects containing all the linked documents, bail if // 1. Any of them doesn't have default namespace, or // 2. Multiple default namespace are found. (this might be possible by tweaking project file). // The refactoring depends on a single default namespace to operate. var defaultNamespaceFromProjects = new HashSet<string>( documents.Select(d => d.Project.DefaultNamespace), syntaxFacts.StringComparer); if (defaultNamespaceFromProjects.Count != 1 || defaultNamespaceFromProjects.First() == null) { return null; } return defaultNamespaceFromProjects.Single(); } /// <summary> /// Try get the relative namespace for <paramref name="namespace"/> based on <paramref name="relativeTo"/>, /// if <paramref name="relativeTo"/> is the containing namespace of <paramref name="namespace"/>. Otherwise, /// Returns null. /// For example: /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is "A.B.C.D", then /// the relative namespace is "C.D". /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is also "A.B", then /// the relative namespace is "". /// - If <paramref name="relativeTo"/> is "" then the relative namespace us <paramref name="namespace"/>. /// </summary> private static string GetRelativeNamespace(string relativeTo, string @namespace, ISyntaxFactsService syntaxFacts) { Debug.Assert(relativeTo != null && @namespace != null); if (syntaxFacts.StringComparer.Equals(@namespace, relativeTo)) { return string.Empty; } else if (relativeTo.Length == 0) { return @namespace; } else if (relativeTo.Length >= @namespace.Length) { return null; } var containingText = relativeTo + "."; var namespacePrefix = @namespace.Substring(0, containingText.Length); return syntaxFacts.StringComparer.Equals(containingText, namespacePrefix) ? @namespace[(relativeTo.Length + 1)..] : null; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.ChangeNamespace; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeRefactorings.SyncNamespace { internal abstract partial class AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> : CodeRefactoringProvider where TNamespaceDeclarationSyntax : SyntaxNode where TCompilationUnitSyntax : SyntaxNode where TMemberDeclarationSyntax : SyntaxNode { internal sealed class State { /// <summary> /// The document in which the refactoring is triggered. /// </summary> public Document Document { get; } /// <summary> /// The applicable container node based on cursor location, /// which will be used to change namespace. /// </summary> public SyntaxNode Container { get; } /// <summary> /// This is the new name we want to change the namespace to. /// Empty string means global namespace, whereas null means change namespace action is not available. /// </summary> public string TargetNamespace { get; } /// <summary> /// This is the part of the declared namespace that is contained in default namespace. /// We will use this to construct target folder to move the file to. /// For example, if default namespace is `A` and declared namespace is `A.B.C`, /// this would be `B.C`. /// </summary> public string RelativeDeclaredNamespace { get; } private State( Document document, SyntaxNode container, string targetNamespace, string relativeDeclaredNamespace) { Document = document; Container = container; TargetNamespace = targetNamespace; RelativeDeclaredNamespace = relativeDeclaredNamespace; } public static async Task<State> CreateAsync( AbstractSyncNamespaceCodeRefactoringProvider<TNamespaceDeclarationSyntax, TCompilationUnitSyntax, TMemberDeclarationSyntax> provider, Document document, TextSpan textSpan, CancellationToken cancellationToken) { // User must put cursor on one of the nodes described below to trigger the refactoring. // For each scenario, all requirements must be met. Some of them are checked by `TryGetApplicableInvocationNodeAsync`, // rest by `IChangeNamespaceService.CanChangeNamespaceAsync`. // // - A namespace declaration node that is the only namespace declaration in the document and all types are declared in it: // 1. No nested namespace declarations (even it's empty). // 2. The cursor is on the name of the namespace declaration. // 3. The name of the namespace is valid (i.e. no errors). // 4. No partial type declared in the namespace. Otherwise its multiple declaration will // end up in different namespace. // // - A compilation unit node that contains no namespace declaration: // 1. The cursor is on the name of first declared type. // 2. No partial type declared in the document. Otherwise its multiple declaration will // end up in different namespace. var applicableNode = await provider.TryGetApplicableInvocationNodeAsync(document, textSpan, cancellationToken).ConfigureAwait(false); if (applicableNode == null) { return null; } var changeNamespaceService = document.GetLanguageService<IChangeNamespaceService>(); var canChange = await changeNamespaceService.CanChangeNamespaceAsync(document, applicableNode, cancellationToken).ConfigureAwait(false); if (!canChange || !IsDocumentPathRootedInProjectFolder(document)) { return null; } var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); // We can't determine what the expected namespace would be without knowing the default namespace. var defaultNamespace = GetDefaultNamespace(document, syntaxFacts); if (defaultNamespace == null) { return null; } string declaredNamespace; if (applicableNode is TCompilationUnitSyntax) { declaredNamespace = string.Empty; } else if (applicableNode is TNamespaceDeclarationSyntax) { var syntaxGenerator = SyntaxGenerator.GetGenerator(document); declaredNamespace = syntaxGenerator.GetName(applicableNode); } else { throw ExceptionUtilities.Unreachable; } // Namespace can't be changed if we can't construct a valid qualified identifier from folder names. // In this case, we might still be able to provide refactoring to move file to new location. var targetNamespace = PathMetadataUtilities.TryBuildNamespaceFromFolders(document.Folders, syntaxFacts, defaultNamespace); // No action required if namespace already matches folders. if (syntaxFacts.StringComparer.Equals(targetNamespace, declaredNamespace)) { return null; } // Only provide "move file" action if default namespace contains declared namespace. // For example, if the default namespace is `Microsoft.CodeAnalysis`, and declared // namespace is `System.Diagnostics`, it's very likely this document is an outlier // in the project and user probably has some special rule for it. var relativeNamespace = GetRelativeNamespace(defaultNamespace, declaredNamespace, syntaxFacts); return new State(document, applicableNode, targetNamespace, relativeNamespace); } /// <summary> /// Determines if the actual file path matches its logical path in project /// which is constructed as [project_root_path]\Logical\Folders\. The refactoring /// is triggered only when the two match. The reason of doing this is we don't really know /// the user's intention of keeping the file path out-of-sync with its logical path. /// </summary> private static bool IsDocumentPathRootedInProjectFolder(Document document) { var projectRoot = PathUtilities.GetDirectoryName(document.Project.FilePath); var folderPath = Path.Combine(document.Folders.ToArray()); var absoluteDircetoryPath = PathUtilities.GetDirectoryName(document.FilePath); var logicalDirectoryPath = PathUtilities.CombineAbsoluteAndRelativePaths(projectRoot, folderPath); return PathUtilities.PathsEqual(absoluteDircetoryPath, logicalDirectoryPath); } private static string GetDefaultNamespace(Document document, ISyntaxFactsService syntaxFacts) { var solution = document.Project.Solution; var linkedIds = document.GetLinkedDocumentIds(); var documents = linkedIds.SelectAsArray(id => solution.GetDocument(id)).Add(document); // For all projects containing all the linked documents, bail if // 1. Any of them doesn't have default namespace, or // 2. Multiple default namespace are found. (this might be possible by tweaking project file). // The refactoring depends on a single default namespace to operate. var defaultNamespaceFromProjects = new HashSet<string>( documents.Select(d => d.Project.DefaultNamespace), syntaxFacts.StringComparer); if (defaultNamespaceFromProjects.Count != 1 || defaultNamespaceFromProjects.First() == null) { return null; } return defaultNamespaceFromProjects.Single(); } /// <summary> /// Try get the relative namespace for <paramref name="namespace"/> based on <paramref name="relativeTo"/>, /// if <paramref name="relativeTo"/> is the containing namespace of <paramref name="namespace"/>. Otherwise, /// Returns null. /// For example: /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is "A.B.C.D", then /// the relative namespace is "C.D". /// - If <paramref name="relativeTo"/> is "A.B" and <paramref name="namespace"/> is also "A.B", then /// the relative namespace is "". /// - If <paramref name="relativeTo"/> is "" then the relative namespace us <paramref name="namespace"/>. /// </summary> private static string GetRelativeNamespace(string relativeTo, string @namespace, ISyntaxFactsService syntaxFacts) { Debug.Assert(relativeTo != null && @namespace != null); if (syntaxFacts.StringComparer.Equals(@namespace, relativeTo)) { return string.Empty; } else if (relativeTo.Length == 0) { return @namespace; } else if (relativeTo.Length >= @namespace.Length) { return null; } var containingText = relativeTo + "."; var namespacePrefix = @namespace.Substring(0, containingText.Length); return syntaxFacts.StringComparer.Equals(containingText, namespacePrefix) ? @namespace[(relativeTo.Length + 1)..] : null; } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Core/Impl/SolutionExplorer/SourceGeneratedFileItems/SourceGeneratedFileItem.BrowseObject.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.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratedFileItem { private class BrowseObject : LocalizableProperties { private readonly SourceGeneratedFileItem _sourceGeneratedFileItem; public BrowseObject(SourceGeneratedFileItem sourceGeneratedFileItem) { _sourceGeneratedFileItem = sourceGeneratedFileItem; } [BrowseObjectDisplayName(nameof(SolutionExplorerShim.Name))] public string Name => _sourceGeneratedFileItem.HintName; public override string GetClassName() => SolutionExplorerShim.Source_Generated_File_Properties; public override string GetComponentName() => _sourceGeneratedFileItem.HintName; } } }
// Licensed to the .NET Foundation under one or more 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.VisualStudio.LanguageServices.Implementation.SolutionExplorer { internal sealed partial class SourceGeneratedFileItem { private class BrowseObject : LocalizableProperties { private readonly SourceGeneratedFileItem _sourceGeneratedFileItem; public BrowseObject(SourceGeneratedFileItem sourceGeneratedFileItem) { _sourceGeneratedFileItem = sourceGeneratedFileItem; } [BrowseObjectDisplayName(nameof(SolutionExplorerShim.Name))] public string Name => _sourceGeneratedFileItem.HintName; public override string GetClassName() => SolutionExplorerShim.Source_Generated_File_Properties; public override string GetComponentName() => _sourceGeneratedFileItem.HintName; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/IntegrationTest/IntegrationTests/CSharp/CSharpKeywordHighlighting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpKeywordHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpKeywordHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpKeywordHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Foreach() { var input = @"class C { void M() { [|foreach|](var c in """") { if(true) [|break|]; else [|continue|]; } } }"; Roslyn.Test.Utilities.MarkupTestFile.GetSpans(input, out var text, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.SetText(text); Verify("foreach", spans); Verify("break", spans); Verify("continue", spans); Verify("in", ImmutableArray.Create<TextSpan>()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void PreprocessorConditionals() { var input = @" #define Debug #undef Trace class PurchaseTransaction { void Commit() { {|if:#if|} Debug CheckConsistency(); {|else:#if|} Trace WriteToLog(this.ToString()); {|else:#else|} Exit(); {|else:#endif|} {|if:#endif|} CommitHelper(); } }"; Test.Utilities.MarkupTestFile.GetSpans( input, out var text, out IDictionary<string, ImmutableArray<TextSpan>> spans); VisualStudio.Editor.SetText(text); Verify("#if", spans["if"]); Verify("#else", spans["else"]); Verify("#endif", spans["else"]); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void PreprocessorRegions() { var input = @" class C { [|#region|] Main static void Main() { } [|#endregion|] }"; Test.Utilities.MarkupTestFile.GetSpans( input, out var text, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.SetText(text); Verify("#region", spans); Verify("#endregion", spans); } private void Verify(string marker, ImmutableArray<TextSpan> expectedCount) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.KeywordHighlighting); Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.IntegrationTest.Utilities; using Roslyn.Test.Utilities; using Xunit; using Xunit.Abstractions; namespace Roslyn.VisualStudio.IntegrationTests.CSharp { [Collection(nameof(SharedIntegrationHostFixture))] public class CSharpKeywordHighlighting : AbstractEditorTest { protected override string LanguageName => LanguageNames.CSharp; public CSharpKeywordHighlighting(VisualStudioInstanceFactory instanceFactory) : base(instanceFactory, nameof(CSharpKeywordHighlighting)) { } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void Foreach() { var input = @"class C { void M() { [|foreach|](var c in """") { if(true) [|break|]; else [|continue|]; } } }"; Roslyn.Test.Utilities.MarkupTestFile.GetSpans(input, out var text, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.SetText(text); Verify("foreach", spans); Verify("break", spans); Verify("continue", spans); Verify("in", ImmutableArray.Create<TextSpan>()); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void PreprocessorConditionals() { var input = @" #define Debug #undef Trace class PurchaseTransaction { void Commit() { {|if:#if|} Debug CheckConsistency(); {|else:#if|} Trace WriteToLog(this.ToString()); {|else:#else|} Exit(); {|else:#endif|} {|if:#endif|} CommitHelper(); } }"; Test.Utilities.MarkupTestFile.GetSpans( input, out var text, out IDictionary<string, ImmutableArray<TextSpan>> spans); VisualStudio.Editor.SetText(text); Verify("#if", spans["if"]); Verify("#else", spans["else"]); Verify("#endif", spans["else"]); } [WpfFact, Trait(Traits.Feature, Traits.Features.Classification)] public void PreprocessorRegions() { var input = @" class C { [|#region|] Main static void Main() { } [|#endregion|] }"; Test.Utilities.MarkupTestFile.GetSpans( input, out var text, out ImmutableArray<TextSpan> spans); VisualStudio.Editor.SetText(text); Verify("#region", spans); Verify("#endregion", spans); } private void Verify(string marker, ImmutableArray<TextSpan> expectedCount) { VisualStudio.Editor.PlaceCaret(marker, charsOffset: -1); VisualStudio.Workspace.WaitForAllAsyncOperations( Helper.HangMitigatingTimeout, FeatureAttribute.Workspace, FeatureAttribute.SolutionCrawler, FeatureAttribute.DiagnosticService, FeatureAttribute.Classification, FeatureAttribute.KeywordHighlighting); Assert.Equal(expectedCount, VisualStudio.Editor.GetKeywordHighlightTags()); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Tools/ExternalAccess/OmniSharp/Structure/OmniSharpBlockStructureOptions.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.Text; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure { internal static class OmniSharpBlockStructureOptions { public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = (PerLanguageOption<bool>)BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions; public static readonly PerLanguageOption<bool> ShowOutliningForCommentsAndPreprocessorRegions = (PerLanguageOption<bool>)BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions; } }
// Licensed to the .NET Foundation under one or more 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.Text; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.Structure { internal static class OmniSharpBlockStructureOptions { public static readonly PerLanguageOption<bool> ShowBlockStructureGuidesForCommentsAndPreprocessorRegions = (PerLanguageOption<bool>)BlockStructureOptions.ShowBlockStructureGuidesForCommentsAndPreprocessorRegions; public static readonly PerLanguageOption<bool> ShowOutliningForCommentsAndPreprocessorRegions = (PerLanguageOption<bool>)BlockStructureOptions.ShowOutliningForCommentsAndPreprocessorRegions; } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/CSharp/Portable/ConvertForToForEach/CSharpConvertForToForEachCodeRefactoringProvider.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.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertForToForEach; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared] internal class CSharpConvertForToForEachCodeRefactoringProvider : AbstractConvertForToForEachCodeRefactoringProvider< StatementSyntax, ForStatementSyntax, ExpressionSyntax, MemberAccessExpressionSyntax, TypeSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertForToForEachCodeRefactoringProvider() { } protected override string GetTitle() => CSharpFeaturesResources.Convert_to_foreach; protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement) => forStatement.Statement is BlockSyntax block ? block.Statements : SyntaxFactory.SingletonList(forStatement.Statement); protected override bool TryGetForStatementComponents( ForStatementSyntax forStatement, out SyntaxToken iterationVariable, out ExpressionSyntax initializer, out MemberAccessExpressionSyntax memberAccess, out ExpressionSyntax stepValueExpressionOpt, CancellationToken cancellationToken) { // Look for very specific forms. Basically, only minor variations around: // for (var i = 0; i < expr.Lenth; i++) if (forStatement.Declaration != null && forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) && forStatement.Incrementors.Count == 1) { var declaration = forStatement.Declaration; if (declaration.Variables.Count == 1) { var declarator = declaration.Variables[0]; if (declarator.Initializer != null) { iterationVariable = declarator.Identifier; initializer = declarator.Initializer.Value; var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition; // Look for: i < expr.Length if (binaryExpression.Left is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText && binaryExpression.Right is MemberAccessExpressionSyntax) { memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right; var incrementor = forStatement.Incrementors[0]; return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt); } } } } iterationVariable = default; memberAccess = null; initializer = null; stepValueExpressionOpt = null; return false; } private static bool TryGetStepValue( SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue) { // support // x++ // ++x // x += constant_1 ExpressionSyntax operand; switch (incrementor.Kind()) { case SyntaxKind.PostIncrementExpression: operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.PreIncrementExpression: operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.AddAssignmentExpression: var assignment = (AssignmentExpressionSyntax)incrementor; operand = assignment.Left; stepValue = assignment.Right; break; default: stepValue = null; return false; } return operand is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText; } protected override SyntaxNode ConvertForNode( ForStatementSyntax forStatement, TypeSyntax typeNode, SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression, ITypeSymbol iterationVariableType, OptionSet optionSet) { typeNode ??= iterationVariableType.GenerateTypeSyntax(); return SyntaxFactory.ForEachStatement( SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword), forStatement.OpenParenToken, typeNode, foreachIdentifier, SyntaxFactory.Token(SyntaxKind.InKeyword), collectionExpression, forStatement.CloseParenToken, forStatement.Statement); } // C# has no special variable declarator forms that would cause us to not be able to convert. protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable) => 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.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.ConvertForToForEach; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; namespace Microsoft.CodeAnalysis.CSharp.ConvertForToForEach { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertForToForEach), Shared] internal class CSharpConvertForToForEachCodeRefactoringProvider : AbstractConvertForToForEachCodeRefactoringProvider< StatementSyntax, ForStatementSyntax, ExpressionSyntax, MemberAccessExpressionSyntax, TypeSyntax, VariableDeclaratorSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpConvertForToForEachCodeRefactoringProvider() { } protected override string GetTitle() => CSharpFeaturesResources.Convert_to_foreach; protected override SyntaxList<StatementSyntax> GetBodyStatements(ForStatementSyntax forStatement) => forStatement.Statement is BlockSyntax block ? block.Statements : SyntaxFactory.SingletonList(forStatement.Statement); protected override bool TryGetForStatementComponents( ForStatementSyntax forStatement, out SyntaxToken iterationVariable, out ExpressionSyntax initializer, out MemberAccessExpressionSyntax memberAccess, out ExpressionSyntax stepValueExpressionOpt, CancellationToken cancellationToken) { // Look for very specific forms. Basically, only minor variations around: // for (var i = 0; i < expr.Lenth; i++) if (forStatement.Declaration != null && forStatement.Condition.IsKind(SyntaxKind.LessThanExpression) && forStatement.Incrementors.Count == 1) { var declaration = forStatement.Declaration; if (declaration.Variables.Count == 1) { var declarator = declaration.Variables[0]; if (declarator.Initializer != null) { iterationVariable = declarator.Identifier; initializer = declarator.Initializer.Value; var binaryExpression = (BinaryExpressionSyntax)forStatement.Condition; // Look for: i < expr.Length if (binaryExpression.Left is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText && binaryExpression.Right is MemberAccessExpressionSyntax) { memberAccess = (MemberAccessExpressionSyntax)binaryExpression.Right; var incrementor = forStatement.Incrementors[0]; return TryGetStepValue(iterationVariable, incrementor, out stepValueExpressionOpt); } } } } iterationVariable = default; memberAccess = null; initializer = null; stepValueExpressionOpt = null; return false; } private static bool TryGetStepValue( SyntaxToken iterationVariable, ExpressionSyntax incrementor, out ExpressionSyntax stepValue) { // support // x++ // ++x // x += constant_1 ExpressionSyntax operand; switch (incrementor.Kind()) { case SyntaxKind.PostIncrementExpression: operand = ((PostfixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.PreIncrementExpression: operand = ((PrefixUnaryExpressionSyntax)incrementor).Operand; stepValue = null; break; case SyntaxKind.AddAssignmentExpression: var assignment = (AssignmentExpressionSyntax)incrementor; operand = assignment.Left; stepValue = assignment.Right; break; default: stepValue = null; return false; } return operand is IdentifierNameSyntax identifierName && identifierName.Identifier.ValueText == iterationVariable.ValueText; } protected override SyntaxNode ConvertForNode( ForStatementSyntax forStatement, TypeSyntax typeNode, SyntaxToken foreachIdentifier, ExpressionSyntax collectionExpression, ITypeSymbol iterationVariableType, OptionSet optionSet) { typeNode ??= iterationVariableType.GenerateTypeSyntax(); return SyntaxFactory.ForEachStatement( SyntaxFactory.Token(SyntaxKind.ForEachKeyword).WithTriviaFrom(forStatement.ForKeyword), forStatement.OpenParenToken, typeNode, foreachIdentifier, SyntaxFactory.Token(SyntaxKind.InKeyword), collectionExpression, forStatement.CloseParenToken, forStatement.Statement); } // C# has no special variable declarator forms that would cause us to not be able to convert. protected override bool IsValidVariableDeclarator(VariableDeclaratorSyntax firstVariable) => true; } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/CSharp/Portable/Completion/CompletionProviders/TupleNameCompletionProvider.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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(TupleNameCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(XmlDocCommentCompletionProvider))] [Shared] internal class TupleNameCompletionProvider : LSPCompletionProvider { private const string ColonString = ":"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TupleNameCompletionProvider() { } public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var cancellationToken = completionContext.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var context = CSharpSyntaxContext.CreateContext(document, semanticModel, position, cancellationToken); var index = GetElementIndex(context); if (index == null) { return; } var typeInferrer = document.GetLanguageService<ITypeInferenceService>(); var inferredTypes = typeInferrer.InferTypes(semanticModel, context.TargetToken.Parent.SpanStart, cancellationToken) .Where(t => t.IsTupleType) .Cast<INamedTypeSymbol>() .ToImmutableArray(); AddItems(inferredTypes, index.Value, completionContext, context.TargetToken.Parent.SpanStart); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static int? GetElementIndex(CSharpSyntaxContext context) { var token = context.TargetToken; if (token.IsKind(SyntaxKind.OpenParenToken)) { if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.CastExpression)) { return 0; } } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TupleExpression)) { var tupleExpr = (TupleExpressionSyntax)context.TargetToken.Parent as TupleExpressionSyntax; return (tupleExpr.Arguments.GetWithSeparators().IndexOf(context.TargetToken) + 1) / 2; } return null; } private static void AddItems(ImmutableArray<INamedTypeSymbol> inferredTypes, int index, CompletionContext context, int spanStart) { foreach (var type in inferredTypes) { if (index >= type.TupleElements.Length) { return; } // Note: the filter text does not include the ':'. We want to ensure that if // the user types the name exactly (up to the colon) that it is selected as an // exact match. var field = type.TupleElements[index]; context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: field.Name, displayTextSuffix: ColonString, symbols: ImmutableArray.Create(field), rules: CompletionItemRules.Default, contextPosition: spanStart, filterText: field.Name)); } } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return Task.FromResult<TextChange?>(new TextChange( selectedItem.Span, selectedItem.DisplayText)); } public override ImmutableHashSet<char> TriggerCharacters => ImmutableHashSet<char>.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; using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Completion; using Microsoft.CodeAnalysis.Completion.Providers; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ErrorReporting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers { [ExportCompletionProvider(nameof(TupleNameCompletionProvider), LanguageNames.CSharp)] [ExtensionOrder(After = nameof(XmlDocCommentCompletionProvider))] [Shared] internal class TupleNameCompletionProvider : LSPCompletionProvider { private const string ColonString = ":"; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public TupleNameCompletionProvider() { } public override async Task ProvideCompletionsAsync(CompletionContext completionContext) { try { var document = completionContext.Document; var position = completionContext.Position; var cancellationToken = completionContext.CancellationToken; var semanticModel = await document.ReuseExistingSpeculativeModelAsync(position, cancellationToken).ConfigureAwait(false); var context = CSharpSyntaxContext.CreateContext(document, semanticModel, position, cancellationToken); var index = GetElementIndex(context); if (index == null) { return; } var typeInferrer = document.GetLanguageService<ITypeInferenceService>(); var inferredTypes = typeInferrer.InferTypes(semanticModel, context.TargetToken.Parent.SpanStart, cancellationToken) .Where(t => t.IsTupleType) .Cast<INamedTypeSymbol>() .ToImmutableArray(); AddItems(inferredTypes, index.Value, completionContext, context.TargetToken.Parent.SpanStart); } catch (Exception e) when (FatalError.ReportAndCatchUnlessCanceled(e)) { // nop } } private static int? GetElementIndex(CSharpSyntaxContext context) { var token = context.TargetToken; if (token.IsKind(SyntaxKind.OpenParenToken)) { if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, SyntaxKind.TupleExpression, SyntaxKind.CastExpression)) { return 0; } } if (token.IsKind(SyntaxKind.CommaToken) && token.Parent.IsKind(SyntaxKind.TupleExpression)) { var tupleExpr = (TupleExpressionSyntax)context.TargetToken.Parent as TupleExpressionSyntax; return (tupleExpr.Arguments.GetWithSeparators().IndexOf(context.TargetToken) + 1) / 2; } return null; } private static void AddItems(ImmutableArray<INamedTypeSymbol> inferredTypes, int index, CompletionContext context, int spanStart) { foreach (var type in inferredTypes) { if (index >= type.TupleElements.Length) { return; } // Note: the filter text does not include the ':'. We want to ensure that if // the user types the name exactly (up to the colon) that it is selected as an // exact match. var field = type.TupleElements[index]; context.AddItem(SymbolCompletionItem.CreateWithSymbolId( displayText: field.Name, displayTextSuffix: ColonString, symbols: ImmutableArray.Create(field), rules: CompletionItemRules.Default, contextPosition: spanStart, filterText: field.Name)); } } protected override Task<TextChange?> GetTextChangeAsync(CompletionItem selectedItem, char? ch, CancellationToken cancellationToken) { return Task.FromResult<TextChange?>(new TextChange( selectedItem.Span, selectedItem.DisplayText)); } public override ImmutableHashSet<char> TriggerCharacters => ImmutableHashSet<char>.Empty; } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/Core/Portable/Workspace/Host/Mef/ExportDynamicFileInfoProviderAttribute.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.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="IDynamicFileInfoProvider"/> implementation for MEF /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal class ExportDynamicFileInfoProviderAttribute : ExportAttribute { /// <summary> /// file extensions this <see cref="IDynamicFileInfoProvider"/> can handle such as cshtml /// /// match will be done by <see cref="StringComparer.OrdinalIgnoreCase"/> /// </summary> public IEnumerable<string> Extensions { get; } public ExportDynamicFileInfoProviderAttribute(params string[] extensions) : base(typeof(IDynamicFileInfoProvider)) { if (extensions?.Length == 0) { throw new ArgumentException(nameof(extensions)); } Extensions = extensions; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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.Composition; namespace Microsoft.CodeAnalysis.Host.Mef { /// <summary> /// Use this attribute to declare a <see cref="IDynamicFileInfoProvider"/> implementation for MEF /// </summary> [MetadataAttribute] [AttributeUsage(AttributeTargets.Class)] internal class ExportDynamicFileInfoProviderAttribute : ExportAttribute { /// <summary> /// file extensions this <see cref="IDynamicFileInfoProvider"/> can handle such as cshtml /// /// match will be done by <see cref="StringComparer.OrdinalIgnoreCase"/> /// </summary> public IEnumerable<string> Extensions { get; } public ExportDynamicFileInfoProviderAttribute(params string[] extensions) : base(typeof(IDynamicFileInfoProvider)) { if (extensions?.Length == 0) { throw new ArgumentException(nameof(extensions)); } Extensions = extensions; } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/VisualBasic/Portable/Symbols/Wrapped/WrappedPropertySymbol.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.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) 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.Globalization Imports System.Threading Imports Microsoft.Cci Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a property that is based on another property. ''' When inheriting from this class, one shouldn't assume that ''' the default behavior it has is appropriate for every case. ''' That behavior should be carefully reviewed and derived type ''' should override behavior as appropriate. ''' </summary> Friend MustInherit Class WrappedPropertySymbol Inherits PropertySymbol Protected _underlyingProperty As PropertySymbol Public ReadOnly Property UnderlyingProperty As PropertySymbol Get Return Me._underlyingProperty End Get End Property Public Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return Me._underlyingProperty.IsImplicitlyDeclared End Get End Property Public Overrides ReadOnly Property ReturnsByRef As Boolean Get Return Me._underlyingProperty.ReturnsByRef End Get End Property Public Overrides ReadOnly Property IsDefault As Boolean Get Return Me._underlyingProperty.IsDefault End Get End Property Friend Overrides ReadOnly Property CallingConvention As CallingConvention Get Return Me._underlyingProperty.CallingConvention End Get End Property Public Overrides ReadOnly Property Name As String Get Return Me._underlyingProperty.Name End Get End Property Friend Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me._underlyingProperty.HasSpecialName End Get End Property Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location) Get Return Me._underlyingProperty.Locations End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return Me._underlyingProperty.DeclaringSyntaxReferences End Get End Property Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility Get Return Me._underlyingProperty.DeclaredAccessibility End Get End Property Public Overrides ReadOnly Property IsShared As Boolean Get Return Me._underlyingProperty.IsShared End Get End Property Public Overrides ReadOnly Property IsOverridable As Boolean Get Return Me._underlyingProperty.IsOverridable End Get End Property Public Overrides ReadOnly Property IsOverrides As Boolean Get Return Me._underlyingProperty.IsOverrides End Get End Property Public Overrides ReadOnly Property IsMustOverride As Boolean Get Return Me._underlyingProperty.IsMustOverride End Get End Property Public Overrides ReadOnly Property IsNotOverridable As Boolean Get Return Me._underlyingProperty.IsNotOverridable End Get End Property Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData Get Return Me._underlyingProperty.ObsoleteAttributeData End Get End Property Public Overrides ReadOnly Property MetadataName As String Get Return Me._underlyingProperty.MetadataName End Get End Property Friend Overrides ReadOnly Property HasRuntimeSpecialName As Boolean Get Return Me._underlyingProperty.HasRuntimeSpecialName End Get End Property Public Sub New(underlyingProperty As PropertySymbol) Debug.Assert(underlyingProperty IsNot Nothing) Me._underlyingProperty = underlyingProperty End Sub Public Overrides Function GetDocumentationCommentXml(Optional preferredCulture As CultureInfo = Nothing, Optional expandIncludes As Boolean = False, Optional cancellationToken As CancellationToken = Nothing) As String Return Me._underlyingProperty.GetDocumentationCommentXml(preferredCulture, expandIncludes, cancellationToken) End Function End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Core/Test/SolutionExplorer/AnalyzersFolderProviderTests.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.ObjectModel Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.Internal.VisualStudio.PlatformUI Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers Imports Microsoft.VisualStudio.Shell Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer <[UseExportProvider]> Public Class AnalyzersFolderProviderTests <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub CreateCollectionSource_NullItem() Using environment = New TestEnvironment() Dim provider As IAttachedCollectionSourceProvider = New AnalyzersFolderItemSourceProvider(environment.Workspace, Nothing) Dim collectionSource = provider.CreateCollectionSource(Nothing, KnownRelationships.Contains) Assert.Null(collectionSource) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub CreateCollectionSource_NullHierarchyIdentity() Using environment = New TestEnvironment() Dim provider As IAttachedCollectionSourceProvider = New AnalyzersFolderItemSourceProvider(environment.Workspace, Nothing) Dim hierarchyItem = New MockHierarchyItem With {.HierarchyIdentity = Nothing} Dim collectionSource = provider.CreateCollectionSource(hierarchyItem, KnownRelationships.Contains) Assert.Null(collectionSource) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub CreateCollectionSource() Using environment = New TestEnvironment() Dim project = CreateVisualBasicProject(environment, "Goo") Dim hierarchy = project.Hierarchy Dim hierarchyItem = New MockHierarchyItem With { .HierarchyIdentity = New MockHierarchyItemIdentity With { .NestedHierarchy = hierarchy, .NestedItemID = MockHierarchy.ReferencesNodeItemId }, .CanonicalName = "References", .Parent = New MockHierarchyItem With { .HierarchyIdentity = New MockHierarchyItemIdentity With { .NestedHierarchy = hierarchy, .NestedItemID = VSConstants.VSITEMID.Root }, .CanonicalName = "Goo" } } Dim provider As IAttachedCollectionSourceProvider = New AnalyzersFolderItemSourceProvider(environment.Workspace, New FakeAnalyzersCommandHandler) Dim collectionSource = provider.CreateCollectionSource(hierarchyItem, KnownRelationships.Contains) Assert.NotNull(collectionSource) Dim items = TryCast(collectionSource.Items, ObservableCollection(Of AnalyzersFolderItem)) Assert.Equal(expected:=1, actual:=items.Count) End Using End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.ObjectModel Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.Internal.VisualStudio.PlatformUI Imports Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.Framework Imports Microsoft.VisualStudio.LanguageServices.UnitTests.ProjectSystemShim.VisualBasicHelpers Imports Microsoft.VisualStudio.Shell Imports Roslyn.Test.Utilities Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.SolutionExplorer <[UseExportProvider]> Public Class AnalyzersFolderProviderTests <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub CreateCollectionSource_NullItem() Using environment = New TestEnvironment() Dim provider As IAttachedCollectionSourceProvider = New AnalyzersFolderItemSourceProvider(environment.Workspace, Nothing) Dim collectionSource = provider.CreateCollectionSource(Nothing, KnownRelationships.Contains) Assert.Null(collectionSource) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub CreateCollectionSource_NullHierarchyIdentity() Using environment = New TestEnvironment() Dim provider As IAttachedCollectionSourceProvider = New AnalyzersFolderItemSourceProvider(environment.Workspace, Nothing) Dim hierarchyItem = New MockHierarchyItem With {.HierarchyIdentity = Nothing} Dim collectionSource = provider.CreateCollectionSource(hierarchyItem, KnownRelationships.Contains) Assert.Null(collectionSource) End Using End Sub <WpfFact, Trait(Traits.Feature, Traits.Features.Diagnostics)> Public Sub CreateCollectionSource() Using environment = New TestEnvironment() Dim project = CreateVisualBasicProject(environment, "Goo") Dim hierarchy = project.Hierarchy Dim hierarchyItem = New MockHierarchyItem With { .HierarchyIdentity = New MockHierarchyItemIdentity With { .NestedHierarchy = hierarchy, .NestedItemID = MockHierarchy.ReferencesNodeItemId }, .CanonicalName = "References", .Parent = New MockHierarchyItem With { .HierarchyIdentity = New MockHierarchyItemIdentity With { .NestedHierarchy = hierarchy, .NestedItemID = VSConstants.VSITEMID.Root }, .CanonicalName = "Goo" } } Dim provider As IAttachedCollectionSourceProvider = New AnalyzersFolderItemSourceProvider(environment.Workspace, New FakeAnalyzersCommandHandler) Dim collectionSource = provider.CreateCollectionSource(hierarchyItem, KnownRelationships.Contains) Assert.NotNull(collectionSource) Dim items = TryCast(collectionSource.Items, ObservableCollection(Of AnalyzersFolderItem)) Assert.Equal(expected:=1, actual:=items.Count) End Using End Sub End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/AnonymousTypeManager.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created in owning compilation. All requests for /// anonymous type symbols go via the instance of this class. /// </summary> internal sealed partial class AnonymousTypeManager : CommonAnonymousTypeManager { internal AnonymousTypeManager(CSharpCompilation compilation) { Debug.Assert(compilation != null); this.Compilation = compilation; } /// <summary> /// Current compilation /// </summary> public CSharpCompilation Compilation { get; } /// <summary> /// Given anonymous type descriptor provided constructs an anonymous type symbol. /// </summary> public NamedTypeSymbol ConstructAnonymousTypeSymbol(AnonymousTypeDescriptor typeDescr) { return new AnonymousTypePublicSymbol(this, typeDescr); } /// <summary> /// Get a symbol of constructed anonymous type property by property index /// </summary> internal static PropertySymbol GetAnonymousTypeProperty(NamedTypeSymbol type, int index) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Properties[index]; } /// <summary> /// Retrieves anonymous type properties types /// </summary> internal static ImmutableArray<TypeWithAnnotations> GetAnonymousTypePropertyTypesWithAnnotations(NamedTypeSymbol type) { Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; var fields = anonymous.TypeDescriptor.Fields; return fields.SelectAsArray(f => f.TypeWithAnnotations); } /// <summary> /// Given an anonymous type and new field types construct a new anonymous type symbol; /// a new type symbol will reuse type descriptor from the constructed type with new type arguments. /// </summary> public static NamedTypeSymbol ConstructAnonymousTypeSymbol(NamedTypeSymbol type, ImmutableArray<TypeWithAnnotations> newFieldTypes) { Debug.Assert(!newFieldTypes.IsDefault); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeSymbol(anonymous.TypeDescriptor.WithNewFieldsTypes(newFieldTypes)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.Symbols; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Manages anonymous types created in owning compilation. All requests for /// anonymous type symbols go via the instance of this class. /// </summary> internal sealed partial class AnonymousTypeManager : CommonAnonymousTypeManager { internal AnonymousTypeManager(CSharpCompilation compilation) { Debug.Assert(compilation != null); this.Compilation = compilation; } /// <summary> /// Current compilation /// </summary> public CSharpCompilation Compilation { get; } /// <summary> /// Given anonymous type descriptor provided constructs an anonymous type symbol. /// </summary> public NamedTypeSymbol ConstructAnonymousTypeSymbol(AnonymousTypeDescriptor typeDescr) { return new AnonymousTypePublicSymbol(this, typeDescr); } /// <summary> /// Get a symbol of constructed anonymous type property by property index /// </summary> internal static PropertySymbol GetAnonymousTypeProperty(NamedTypeSymbol type, int index) { Debug.Assert((object)type != null); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Properties[index]; } /// <summary> /// Retrieves anonymous type properties types /// </summary> internal static ImmutableArray<TypeWithAnnotations> GetAnonymousTypePropertyTypesWithAnnotations(NamedTypeSymbol type) { Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; var fields = anonymous.TypeDescriptor.Fields; return fields.SelectAsArray(f => f.TypeWithAnnotations); } /// <summary> /// Given an anonymous type and new field types construct a new anonymous type symbol; /// a new type symbol will reuse type descriptor from the constructed type with new type arguments. /// </summary> public static NamedTypeSymbol ConstructAnonymousTypeSymbol(NamedTypeSymbol type, ImmutableArray<TypeWithAnnotations> newFieldTypes) { Debug.Assert(!newFieldTypes.IsDefault); Debug.Assert(type.IsAnonymousType); var anonymous = (AnonymousTypePublicSymbol)type; return anonymous.Manager.ConstructAnonymousTypeSymbol(anonymous.TypeDescriptor.WithNewFieldsTypes(newFieldTypes)); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.CodeTypeRefData.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class CodeTypeRefData Public Property CodeTypeFullName As String Public Property TypeKind As EnvDTE.vsCMTypeRef = EnvDTE.vsCMTypeRef.vsCMTypeRefOther Public Property AsString As String Public Property AsFullName As String End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class CodeTypeRefData Public Property CodeTypeFullName As String Public Property TypeKind As EnvDTE.vsCMTypeRef = EnvDTE.vsCMTypeRef.vsCMTypeRefOther Public Property AsString As String Public Property AsFullName As String End Class End Class End Namespace
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/EditorFeatures/Core/FindUsages/AbstractFindUsagesService.ProgressAdapter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IStreamingFindLiteralReferencesProgress"/> calls to an /// <see cref="IFindUsagesContext"/> instance. /// </summary> private class FindLiteralsProgressAdapter : IStreamingFindLiteralReferencesProgress { private readonly IFindUsagesContext _context; private readonly DefinitionItem _definition; public IStreamingProgressTracker ProgressTracker => _context.ProgressTracker; public FindLiteralsProgressAdapter( IFindUsagesContext context, DefinitionItem definition) { _context = context; _definition = definition; } public async ValueTask OnReferenceFoundAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync( document, span, cancellationToken).ConfigureAwait(false); await _context.OnReferenceFoundAsync( new SourceReferenceItem(_definition, documentSpan, SymbolUsageInfo.None), cancellationToken).ConfigureAwait(false); } } /// <summary> /// Forwards IFindReferencesProgress calls to an IFindUsagesContext instance. /// </summary> private class FindReferencesProgressAdapter : IStreamingFindReferencesProgress { private readonly Solution _solution; private readonly IFindUsagesContext _context; private readonly FindReferencesSearchOptions _options; /// <summary> /// We will hear about definition symbols many times while performing FAR. We'll /// here about it first when the FAR engine discovers the symbol, and then for every /// reference it finds to the symbol. However, we only want to create and pass along /// a single instance of <see cref="INavigableItem" /> for that definition no matter /// how many times we see it. /// /// This dictionary allows us to make that mapping once and then keep it around for /// all future callbacks. /// </summary> private readonly Dictionary<SymbolGroup, DefinitionItem> _definitionToItem = new(); private readonly SemaphoreSlim _gate = new(initialCount: 1); public IStreamingProgressTracker ProgressTracker => _context.ProgressTracker; public FindReferencesProgressAdapter( Solution solution, IFindUsagesContext context, FindReferencesSearchOptions options) { _solution = solution; _context = context; _options = options; } // Do nothing functions. The streaming far service doesn't care about // any of these. public ValueTask OnStartedAsync(CancellationToken cancellationToken) => default; public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => default; public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => default; public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => default; // More complicated forwarding functions. These need to map from the symbols // used by the FAR engine to the INavigableItems used by the streaming FAR // feature. private async ValueTask<DefinitionItem> GetDefinitionItemAsync(SymbolGroup group, CancellationToken cancellationToken) { using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_definitionToItem.TryGetValue(group, out var definitionItem)) { definitionItem = await group.ToClassifiedDefinitionItemAsync( _solution, isPrimary: _definitionToItem.Count == 0, includeHiddenLocations: false, _options, cancellationToken).ConfigureAwait(false); _definitionToItem[group] = definitionItem; } return definitionItem; } } public async ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) { var definitionItem = await GetDefinitionItemAsync(group, cancellationToken).ConfigureAwait(false); await _context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync(SymbolGroup group, ISymbol definition, ReferenceLocation location, CancellationToken cancellationToken) { var definitionItem = await GetDefinitionItemAsync(group, cancellationToken).ConfigureAwait(false); var referenceItem = await location.TryCreateSourceReferenceItemAsync( definitionItem, includeHiddenLocations: false, cancellationToken).ConfigureAwait(false); if (referenceItem != null) await _context.OnReferenceFoundAsync(referenceItem, cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.FindUsages; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Editor.FindUsages { internal abstract partial class AbstractFindUsagesService { /// <summary> /// Forwards <see cref="IStreamingFindLiteralReferencesProgress"/> calls to an /// <see cref="IFindUsagesContext"/> instance. /// </summary> private class FindLiteralsProgressAdapter : IStreamingFindLiteralReferencesProgress { private readonly IFindUsagesContext _context; private readonly DefinitionItem _definition; public IStreamingProgressTracker ProgressTracker => _context.ProgressTracker; public FindLiteralsProgressAdapter( IFindUsagesContext context, DefinitionItem definition) { _context = context; _definition = definition; } public async ValueTask OnReferenceFoundAsync(Document document, TextSpan span, CancellationToken cancellationToken) { var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync( document, span, cancellationToken).ConfigureAwait(false); await _context.OnReferenceFoundAsync( new SourceReferenceItem(_definition, documentSpan, SymbolUsageInfo.None), cancellationToken).ConfigureAwait(false); } } /// <summary> /// Forwards IFindReferencesProgress calls to an IFindUsagesContext instance. /// </summary> private class FindReferencesProgressAdapter : IStreamingFindReferencesProgress { private readonly Solution _solution; private readonly IFindUsagesContext _context; private readonly FindReferencesSearchOptions _options; /// <summary> /// We will hear about definition symbols many times while performing FAR. We'll /// here about it first when the FAR engine discovers the symbol, and then for every /// reference it finds to the symbol. However, we only want to create and pass along /// a single instance of <see cref="INavigableItem" /> for that definition no matter /// how many times we see it. /// /// This dictionary allows us to make that mapping once and then keep it around for /// all future callbacks. /// </summary> private readonly Dictionary<SymbolGroup, DefinitionItem> _definitionToItem = new(); private readonly SemaphoreSlim _gate = new(initialCount: 1); public IStreamingProgressTracker ProgressTracker => _context.ProgressTracker; public FindReferencesProgressAdapter( Solution solution, IFindUsagesContext context, FindReferencesSearchOptions options) { _solution = solution; _context = context; _options = options; } // Do nothing functions. The streaming far service doesn't care about // any of these. public ValueTask OnStartedAsync(CancellationToken cancellationToken) => default; public ValueTask OnCompletedAsync(CancellationToken cancellationToken) => default; public ValueTask OnFindInDocumentStartedAsync(Document document, CancellationToken cancellationToken) => default; public ValueTask OnFindInDocumentCompletedAsync(Document document, CancellationToken cancellationToken) => default; // More complicated forwarding functions. These need to map from the symbols // used by the FAR engine to the INavigableItems used by the streaming FAR // feature. private async ValueTask<DefinitionItem> GetDefinitionItemAsync(SymbolGroup group, CancellationToken cancellationToken) { using (await _gate.DisposableWaitAsync(cancellationToken).ConfigureAwait(false)) { if (!_definitionToItem.TryGetValue(group, out var definitionItem)) { definitionItem = await group.ToClassifiedDefinitionItemAsync( _solution, isPrimary: _definitionToItem.Count == 0, includeHiddenLocations: false, _options, cancellationToken).ConfigureAwait(false); _definitionToItem[group] = definitionItem; } return definitionItem; } } public async ValueTask OnDefinitionFoundAsync(SymbolGroup group, CancellationToken cancellationToken) { var definitionItem = await GetDefinitionItemAsync(group, cancellationToken).ConfigureAwait(false); await _context.OnDefinitionFoundAsync(definitionItem, cancellationToken).ConfigureAwait(false); } public async ValueTask OnReferenceFoundAsync(SymbolGroup group, ISymbol definition, ReferenceLocation location, CancellationToken cancellationToken) { var definitionItem = await GetDefinitionItemAsync(group, cancellationToken).ConfigureAwait(false); var referenceItem = await location.TryCreateSourceReferenceItemAsync( definitionItem, includeHiddenLocations: false, cancellationToken).ConfigureAwait(false); if (referenceItem != null) await _context.OnReferenceFoundAsync(referenceItem, cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Compilers/CSharp/Test/Emit/Emit/CompilationEmitTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public partial class CompilationEmitTests : EmitMetadataTestBase { [Fact] public void CompilationEmitDiagnostics() { // Check that Compilation.Emit actually produces compilation errors. string source = @" class X { public void Main() { const int x = 5; x = x; // error; assigning to const. } }"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } emitResult.Diagnostics.Verify( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "x")); } [Fact] public void CompilationEmitWithQuotedMainType() { // Check that compilation with quoted main switch argument produce diagnostic. // MSBuild can return quoted main argument value which is removed from the command line arguments or by parsing // command line arguments, but we DO NOT unquote arguments which are provided by // the WithMainTypeName function - (was originally exposed through using // a Cyrillic Namespace And building Using MSBuild.) string source = @" namespace abc { public class X { public static void Main() { } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("abc.X")); compilation.VerifyDiagnostics(); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("\"abc.X\"")); compilation.VerifyDiagnostics(// error CS1555: Could not find '"abc.X"' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("\"abc.X\"")); // Verify use of Cyrillic namespace results in same behavior source = @" namespace решения { public class X { public static void Main() { } } }"; compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("решения.X")); compilation.VerifyDiagnostics(); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("\"решения.X\"")); compilation.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("\"решения.X\"")); } [Fact] public void CompilationGetDiagnostics() { // Check that Compilation.GetDiagnostics and Compilation.GetDeclarationDiagnostics work as expected. string source = @" class X { private Blah q; public void Main() { const int x = 5; x = x; // error; assigning to const. } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,13): error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) // private Blah q; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Blah").WithArguments("Blah"), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // x = x; // error; assigning to const. Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "x"), // (4,18): warning CS0169: The field 'X.q' is never used // private Blah q; Diagnostic(ErrorCode.WRN_UnreferencedField, "q").WithArguments("X.q")); } // Check that Emit produces syntax, declaration, and method body errors. [Fact] public void EmitDiagnostics() { CSharpCompilation comp = CreateCompilation(@" namespace N { class X { public Blah field; private static readonly int ro; public static void Main() { ro = 4; } } } namespace N.; "); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = comp.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.False(emitResult.Success); emitResult.Diagnostics.Verify( // (13,13): error CS1001: Identifier expected // namespace N.; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(13, 13), // (13,11): error CS8942: File-scoped namespace must precede all other members in a file. // namespace N.; Diagnostic(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, "N.").WithLocation(13, 11), // (4,16): error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) // public Blah field; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Blah").WithArguments("Blah").WithLocation(4, 16), // (8,13): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) // ro = 4; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, "ro").WithLocation(8, 13), // (4,21): warning CS0649: Field 'X.field' is never assigned to, and will always have its default value null // public Blah field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("N.X.field", "null").WithLocation(4, 21)); } // Check that EmitMetadataOnly works [Fact] public void EmitMetadataOnly() { CSharpCompilation comp = CreateCompilation(@" namespace Goo.Bar { public class Test1 { public static void SayHello() { Console.WriteLine(""hello""); } public int x; private int y; public Test1() { x = 17; } public string goo(int a) { return a.ToString(); } } } "); EmitResult emitResult; byte[] mdOnlyImage; using (var output = new MemoryStream()) { emitResult = comp.Emit(output, options: new EmitOptions(metadataOnly: true)); mdOnlyImage = output.ToArray(); } Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); Assert.True(mdOnlyImage.Length > 0, "no metadata emitted"); var srcUsing = @" using System; using Goo.Bar; class Test2 { public static void Main() { Test1.SayHello(); Console.WriteLine(new Test1().x); } } "; CSharpCompilation compUsing = CreateCompilation(srcUsing, new[] { MetadataReference.CreateFromImage(mdOnlyImage.AsImmutableOrNull()) }); using (var output = new MemoryStream()) { emitResult = compUsing.Emit(output); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); Assert.True(output.ToArray().Length > 0, "no metadata emitted"); } } [Fact] public void EmitRefAssembly_PrivateMain() { CSharpCompilation comp = CreateCompilation(@" public class C { internal static void Main() { System.Console.WriteLine(""hello""); } } ", options: TestOptions.DebugExe); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { // Previously, this would crash when trying to get the entry point for the ref assembly // (but the Main method is not emitted in the ref assembly...) EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyEntryPoint(output, expectZero: false); VerifyMethods(output, "C", new[] { "void C.Main()", "C..ctor()" }); VerifyMvid(output, hasMvidSection: false); VerifyEntryPoint(metadataOutput, expectZero: true); VerifyMethods(metadataOutput, "C", new[] { "C..ctor()" }); VerifyMvid(metadataOutput, hasMvidSection: true); } void VerifyEntryPoint(MemoryStream stream, bool expectZero) { stream.Position = 0; int entryPoint = new PEHeaders(stream).CorHeader.EntryPointTokenOrRelativeVirtualAddress; Assert.Equal(expectZero, entryPoint == 0); } } private class TestResourceSectionBuilder : ResourceSectionBuilder { public TestResourceSectionBuilder() { } protected override void Serialize(BlobBuilder builder, SectionLocation location) { builder.WriteInt32(0x12345678); builder.WriteInt32(location.PointerToRawData); builder.WriteInt32(location.RelativeVirtualAddress); } } private class TestPEBuilder : ManagedPEBuilder { public static readonly Guid s_mvid = Guid.Parse("a78fa2c3-854e-42bf-8b8d-75a450a6dc18"); public TestPEBuilder(PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, ResourceSectionBuilder nativeResources) : base(header, metadataRootBuilder, ilStream, nativeResources: nativeResources) { } protected override ImmutableArray<Section> CreateSections() { return base.CreateSections().Add( new Section(".mvid", SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable)); } protected override BlobBuilder SerializeSection(string name, SectionLocation location) { if (name.Equals(".mvid", StringComparison.Ordinal)) { var sectionBuilder = new BlobBuilder(); sectionBuilder.WriteGuid(s_mvid); return sectionBuilder; } return base.SerializeSection(name, location); } } [Fact] public void MvidSectionNotFirst() { var ilBuilder = new BlobBuilder(); var metadataBuilder = new MetadataBuilder(); var peBuilder = new TestPEBuilder( PEHeaderBuilder.CreateLibraryHeader(), new MetadataRootBuilder(metadataBuilder), ilBuilder, nativeResources: new TestResourceSectionBuilder()); var peBlob = new BlobBuilder(); peBuilder.Serialize(peBlob); var peStream = new MemoryStream(); peBlob.WriteContentTo(peStream); peStream.Position = 0; using (var peReader = new PEReader(peStream)) { AssertEx.Equal(new[] { ".text", ".rsrc", ".reloc", ".mvid" }, peReader.PEHeaders.SectionHeaders.Select(h => h.Name)); peStream.Position = 0; var mvid = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(peStream); Assert.Equal(TestPEBuilder.s_mvid, mvid); } } /// <summary> /// Extract the MVID using two different methods (PEReader and MvidReader) and compare them. /// We only expect an .mvid section in ref assemblies. /// </summary> private void VerifyMvid(MemoryStream stream, bool hasMvidSection) { stream.Position = 0; using (var reader = new PEReader(stream)) { var metadataReader = reader.GetMetadataReader(); Guid mvidFromModuleDefinition = metadataReader.GetGuid(metadataReader.GetModuleDefinition().Mvid); stream.Position = 0; var mvidFromMvidReader = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(stream); Assert.NotEqual(Guid.Empty, mvidFromModuleDefinition); if (hasMvidSection) { Assert.Equal(mvidFromModuleDefinition, mvidFromMvidReader); } else { Assert.Equal(Guid.Empty, mvidFromMvidReader); } } } [Fact] public void EmitRefAssembly_PrivatePropertySetter() { CSharpCompilation comp = CreateCompilation(@" public class C { public int PrivateSetter { get; private set; } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyMethods(output, "C", new[] { "System.Int32 C.<PrivateSetter>k__BackingField", "System.Int32 C.PrivateSetter.get", "void C.PrivateSetter.set", "C..ctor()", "System.Int32 C.PrivateSetter { get; private set; }" }); VerifyMethods(metadataOutput, "C", new[] { "System.Int32 C.PrivateSetter.get", "C..ctor()", "System.Int32 C.PrivateSetter { get; }" }); VerifyMvid(output, hasMvidSection: false); VerifyMvid(metadataOutput, hasMvidSection: true); } } [Fact] public void EmitRefAssembly_PrivatePropertyGetter() { CSharpCompilation comp = CreateCompilation(@" public class C { public int PrivateGetter { private get; set; } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyMethods(output, "C", new[] { "System.Int32 C.<PrivateGetter>k__BackingField", "System.Int32 C.PrivateGetter.get", "void C.PrivateGetter.set", "C..ctor()", "System.Int32 C.PrivateGetter { private get; set; }" }); VerifyMethods(metadataOutput, "C", new[] { "void C.PrivateGetter.set", "C..ctor()", "System.Int32 C.PrivateGetter { set; }" }); } } [Fact] public void EmitRefAssembly_PrivateIndexerGetter() { CSharpCompilation comp = CreateCompilation(@" public class C { public int this[int i] { private get { return 0; } set { } } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyMethods(output, "C", new[] { "System.Int32 C.this[System.Int32 i].get", "void C.this[System.Int32 i].set", "C..ctor()", "System.Int32 C.this[System.Int32 i] { private get; set; }" }); VerifyMethods(metadataOutput, "C", new[] { "void C.this[System.Int32 i].set", "C..ctor()", "System.Int32 C.this[System.Int32 i] { set; }" }); } } [Fact] public void EmitRefAssembly_SealedPropertyWithInternalInheritedGetter() { CSharpCompilation comp = CreateCompilation(@" public class Base { public virtual int Property { internal get { return 0; } set { } } } public class C : Base { public sealed override int Property { set { } } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); emitResult.Diagnostics.Verify(); Assert.True(emitResult.Success); VerifyMethods(output, "C", new[] { "void C.Property.set", "C..ctor()", "System.Int32 C.Property.get", "System.Int32 C.Property { internal get; set; }" }); // A getter is synthesized on C.Property so that it can be marked as sealed. It is emitted despite being internal because it is virtual. VerifyMethods(metadataOutput, "C", new[] { "void C.Property.set", "C..ctor()", "System.Int32 C.Property.get", "System.Int32 C.Property { internal get; set; }" }); } } [Fact] public void EmitRefAssembly_PrivateAccessorOnEvent() { CSharpCompilation comp = CreateCompilation(@" public class C { public event System.Action PrivateAdder { private add { } remove { } } public event System.Action PrivateRemover { add { } private remove { } } } "); comp.VerifyDiagnostics( // (4,47): error CS1609: Modifiers cannot be placed on event accessor declarations // public event System.Action PrivateAdder { private add { } remove { } } Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "private").WithLocation(4, 47), // (5,57): error CS1609: Modifiers cannot be placed on event accessor declarations // public event System.Action PrivateRemover { add { } private remove { } } Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "private").WithLocation(5, 57) ); } [Fact] [WorkItem(38444, "https://github.com/dotnet/roslyn/issues/38444")] public void EmitRefAssembly_InternalAttributeConstructor() { CSharpCompilation comp = CreateCompilation(@" using System; internal class SomeAttribute : Attribute { internal SomeAttribute() { } } [Some] public class C { } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); emitResult.Diagnostics.Verify(); Assert.True(emitResult.Success); VerifyMethods(output, "C", new[] { "C..ctor()" }); VerifyMethods(metadataOutput, "C", new[] { "C..ctor()" }); VerifyMethods(output, "SomeAttribute", new[] { "SomeAttribute..ctor()" }); VerifyMethods(metadataOutput, "SomeAttribute", new[] { "SomeAttribute..ctor()" }); } } [Fact] [WorkItem(38444, "https://github.com/dotnet/roslyn/issues/38444")] public void EmitRefAssembly_InternalAttributeConstructor_DoesntIncludeMethodsOrStaticConstructors() { CSharpCompilation comp = CreateCompilation(@" using System; internal class SomeAttribute : Attribute { internal SomeAttribute() { } static SomeAttribute() { } internal void F() { } } [Some] public class C { } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); emitResult.Diagnostics.Verify(); Assert.True(emitResult.Success); VerifyMethods(output, "C", new[] { "C..ctor()" }); VerifyMethods(metadataOutput, "C", new[] { "C..ctor()" }); VerifyMethods(output, "SomeAttribute", new[] { "SomeAttribute..ctor()", "SomeAttribute..cctor()", "void SomeAttribute.F()" }); VerifyMethods(metadataOutput, "SomeAttribute", new[] { "SomeAttribute..ctor()" }); } } private static void VerifyMethods(MemoryStream stream, string containingType, string[] expectedMethods) { stream.Position = 0; var metadataRef = AssemblyMetadata.CreateFromImage(stream.ToArray()).GetReference(); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( expectedMethods, compWithMetadata.GetMember<NamedTypeSymbol>(containingType).GetMembers().Select(m => m.ToTestDisplayString())); } [Fact] public void RefAssembly_HasReferenceAssemblyAttribute() { var emitRefAssembly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var attributes = reader.GetAssemblyDefinition().GetCustomAttributes(); AssertEx.Equal(new[] { "MemberReference:Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor(Int32)", "MemberReference:Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor()", "MemberReference:Void System.Diagnostics.DebuggableAttribute..ctor(DebuggingModes)", "MemberReference:Void System.Runtime.CompilerServices.ReferenceAssemblyAttribute..ctor()" }, attributes.Select(a => MetadataReaderUtils.Dump(reader, reader.GetCustomAttribute(a).Constructor))); }; CompileAndVerify("", emitOptions: emitRefAssembly, assemblyValidator: assemblyValidator); } [Fact] public void RefAssembly_HandlesMissingReferenceAssemblyAttribute() { var emitRefAssembly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var attributes = reader.GetAssemblyDefinition().GetCustomAttributes(); AssertEx.SetEqual(attributes.Select(a => MetadataReaderUtils.Dump(reader, reader.GetCustomAttribute(a).Constructor)), new string[] { "MemberReference:Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor(Int32)", "MemberReference:Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor()", "MemberReference:Void System.Diagnostics.DebuggableAttribute..ctor(DebuggingModes)" }); }; var comp = CreateCompilation(""); comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor); CompileAndVerifyCommon(compilation: comp, emitOptions: emitRefAssembly, assemblyValidator: assemblyValidator); } [Fact] public void RefAssembly_ReferenceAssemblyAttributeAlsoInSource() { var emitRefAssembly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var attributes = reader.GetAssemblyDefinition().GetCustomAttributes(); AssertEx.Equal(new string[] { "MemberReference:Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor(Int32)", "MemberReference:Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor()", "MemberReference:Void System.Diagnostics.DebuggableAttribute..ctor(DebuggingModes)", "MemberReference:Void System.Runtime.CompilerServices.ReferenceAssemblyAttribute..ctor()" }, attributes.Select(a => MetadataReaderUtils.Dump(reader, reader.GetCustomAttribute(a).Constructor))); }; string source = @"[assembly:System.Runtime.CompilerServices.ReferenceAssembly()]"; CompileAndVerify(source, emitOptions: emitRefAssembly, assemblyValidator: assemblyValidator); } [Theory] [InlineData("public int M() { return 1; }", "public int M() { return 2; }", Match.BothMetadataAndRefOut)] [InlineData("public int M() { return 1; }", "public int M() { error(); }", Match.BothMetadataAndRefOut)] [InlineData("private void M() { }", "", Match.RefOut)] [InlineData("internal void M() { }", "", Match.RefOut)] [InlineData("private protected void M() { }", "", Match.RefOut)] [InlineData("private void M() { dynamic x = 1; }", "", Match.RefOut)] // no reference added from method bodies [InlineData(@"private void M() { var x = new { id = 1 }; }", "", Match.RefOut)] [InlineData("private int P { get { Error(); } set { Error(); } }", "", Match.RefOut)] // errors in methods bodies don't matter [InlineData("public int P { get; set; }", "", Match.Different)] [InlineData("protected int P { get; set; }", "", Match.Different)] [InlineData("private int P { get; set; }", "", Match.RefOut)] // private auto-property and underlying field are removed [InlineData("internal int P { get; set; }", "", Match.RefOut)] [InlineData("private event Action E { add { Error(); } remove { Error(); } }", "", Match.RefOut)] [InlineData("internal event Action E { add { Error(); } remove { Error(); } }", "", Match.RefOut)] [InlineData("private class C2 { }", "", Match.Different)] // all types are included [InlineData("private struct S { }", "", Match.Different)] [InlineData("public struct S { private int i; }", "public struct S { }", Match.Different)] [InlineData("private int i;", "", Match.RefOut)] [InlineData("public C() { }", "", Match.BothMetadataAndRefOut)] public void RefAssembly_InvariantToSomeChanges(string left, string right, Match expectedMatch) { string sourceTemplate = @" using System; public class C { CHANGE } "; CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: true); CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: false); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void RefAssembly_NoPia() { string piaSource = @" using System; using System.Runtime.InteropServices; [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [assembly: ImportedFromTypeLib(""Pia1.dll"")] public struct S { public int field; } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest1 { S M(); }"; var pia = CreateCompilation(piaSource, options: TestOptions.ReleaseDll, assemblyName: "pia"); pia.VerifyEmitDiagnostics(); string source = @" public class D : ITest1 { public S M() { throw null; } } "; var piaImageReference = pia.EmitToImageReference(embedInteropTypes: true); verifyRefOnly(piaImageReference); verifyRefOut(piaImageReference); var piaMetadataReference = pia.ToMetadataReference(embedInteropTypes: true); verifyRefOnly(piaMetadataReference); verifyRefOut(piaMetadataReference); void verifyRefOnly(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new MetadataReference[] { reference }); var refOnlyImage = EmitRefOnly(comp); verifyNoPia(refOnlyImage); } void verifyRefOut(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { reference }); var (image, refImage) = EmitRefOut(comp); verifyNoPia(image); verifyNoPia(refImage); } void verifyNoPia(ImmutableArray<byte> image) { var reference = CompilationVerifier.LoadTestEmittedExecutableForSymbolValidation(image, OutputKind.DynamicallyLinkedLibrary); var comp = CreateCompilation("", references: new[] { reference }); var referencedAssembly = comp.GetReferencedAssemblySymbol(reference); var module = (PEModuleSymbol)referencedAssembly.Modules[0]; var itest1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("ITest1"); Assert.NotNull(itest1.GetAttribute("System.Runtime.InteropServices", "TypeIdentifierAttribute")); var method = (PEMethodSymbol)itest1.GetMember("M"); Assert.Equal("S ITest1.M()", method.ToTestDisplayString()); var s = (NamedTypeSymbol)method.ReturnType; Assert.Equal("S", s.ToTestDisplayString()); Assert.NotNull(s.GetAttribute("System.Runtime.InteropServices", "TypeIdentifierAttribute")); var field = s.GetMember("field"); Assert.Equal("System.Int32 S.field", field.ToTestDisplayString()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void RefAssembly_NoPia_ReferenceFromMethodBody() { string piaSource = @" using System; using System.Runtime.InteropServices; [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [assembly: ImportedFromTypeLib(""Pia1.dll"")] public struct S { public int field; } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest1 { S M(); }"; var pia = CreateCompilation(piaSource, options: TestOptions.ReleaseDll, assemblyName: "pia"); pia.VerifyEmitDiagnostics(); string source = @" public class D { public void M2() { ITest1 x = null; S s = x.M(); } } "; var piaImageReference = pia.EmitToImageReference(embedInteropTypes: true); verifyRefOnly(piaImageReference); verifyRefOut(piaImageReference); var piaMetadataReference = pia.ToMetadataReference(embedInteropTypes: true); verifyRefOnly(piaMetadataReference); verifyRefOut(piaMetadataReference); void verifyRefOnly(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new MetadataReference[] { reference }); var refOnlyImage = EmitRefOnly(comp); verifyNoPia(refOnlyImage, expectMissing: true); } void verifyRefOut(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new MetadataReference[] { reference }); var (image, refImage) = EmitRefOut(comp); verifyNoPia(image, expectMissing: false); verifyNoPia(refImage, expectMissing: false); } // The ref assembly produced by refout has more types than that produced by refonly, // because refout will bind the method bodies (and therefore populate more referenced types). // This will be refined in the future. Follow-up issue: https://github.com/dotnet/roslyn/issues/19403 void verifyNoPia(ImmutableArray<byte> image, bool expectMissing) { var reference = CompilationVerifier.LoadTestEmittedExecutableForSymbolValidation(image, OutputKind.DynamicallyLinkedLibrary); var comp = CreateCompilation("", references: new[] { reference }); var referencedAssembly = comp.GetReferencedAssemblySymbol(reference); var module = (PEModuleSymbol)referencedAssembly.Modules[0]; var itest1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("ITest1"); if (expectMissing) { Assert.Null(itest1); Assert.Null(module.GlobalNamespace.GetMember<NamedTypeSymbol>("S")); return; } Assert.NotNull(itest1.GetAttribute("System.Runtime.InteropServices", "TypeIdentifierAttribute")); var method = (PEMethodSymbol)itest1.GetMember("M"); Assert.Equal("S ITest1.M()", method.ToTestDisplayString()); var s = (NamedTypeSymbol)method.ReturnType; Assert.Equal("S", s.ToTestDisplayString()); var field = s.GetMember("field"); Assert.Equal("System.Int32 S.field", field.ToTestDisplayString()); } } [Theory] [InlineData("internal void M() { }", "", Match.Different)] [InlineData("private protected void M() { }", "", Match.Different)] public void RefAssembly_InvariantToSomeChangesWithInternalsVisibleTo(string left, string right, Match expectedMatch) { string sourceTemplate = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleToAttribute(""Friend"")] public class C { CHANGE } "; CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: true); CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: false); } public enum Match { BothMetadataAndRefOut, RefOut, Different } /// <summary> /// Are the metadata-only assemblies identical with two source code modifications? /// Metadata-only assemblies can either include private/internal members or not. /// </summary> private static void CompareAssemblies(string sourceTemplate, string change1, string change2, Match expectedMatch, bool includePrivateMembers) { bool expectMatch = includePrivateMembers ? expectedMatch == Match.BothMetadataAndRefOut : (expectedMatch == Match.BothMetadataAndRefOut || expectedMatch == Match.RefOut); string name = GetUniqueName(); string source1 = sourceTemplate.Replace("CHANGE", change1); CSharpCompilation comp1 = CreateCompilation(Parse(source1), options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); var image1 = comp1.EmitToStream(EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(includePrivateMembers)); var source2 = sourceTemplate.Replace("CHANGE", change2); Compilation comp2 = CreateCompilation(Parse(source2), options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); var image2 = comp2.EmitToStream(EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(includePrivateMembers)); if (expectMatch) { AssertEx.Equal(image1.GetBuffer(), image2.GetBuffer(), message: $"Expecting match for includePrivateMembers={includePrivateMembers} case, but differences were found."); } else { AssertEx.NotEqual(image1.GetBuffer(), image2.GetBuffer(), message: $"Expecting difference for includePrivateMembers={includePrivateMembers} case, but they matched."); } var mvid1 = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(image1); var mvid2 = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(image2); if (!includePrivateMembers) { Assert.NotEqual(Guid.Empty, mvid1); Assert.Equal(expectMatch, mvid1 == mvid2); } else { Assert.Equal(Guid.Empty, mvid1); Assert.Equal(Guid.Empty, mvid2); } } #if NET472 [ConditionalFact(typeof(DesktopOnly))] [WorkItem(31197, "https://github.com/dotnet/roslyn/issues/31197")] public void RefAssembly_InvariantToResourceChanges() { var arrayOfEmbeddedData1 = new byte[] { 1, 2, 3, 4, 5 }; var arrayOfEmbeddedData2 = new byte[] { 1, 2, 3, 4, 5, 6 }; IEnumerable<ResourceDescription> manifestResources1 = new[] { new ResourceDescription(resourceName: "A", fileName: "x.goo", () => new MemoryStream(arrayOfEmbeddedData1), isPublic: true)}; IEnumerable<ResourceDescription> manifestResources2 = new[] { new ResourceDescription(resourceName: "A", fileName: "x.goo", () => new MemoryStream(arrayOfEmbeddedData2), isPublic: true)}; verify(); manifestResources1 = new[] { new ResourceDescription(resourceName: "A", () => new MemoryStream(arrayOfEmbeddedData1), isPublic: true)}; // embedded manifestResources2 = new[] { new ResourceDescription(resourceName: "A", () => new MemoryStream(arrayOfEmbeddedData2), isPublic: true)}; // embedded verify(); void verify() { // Verify refout string name = GetUniqueName(); var (image1, metadataImage1) = emitRefOut(manifestResources1, name); var (image2, metadataImage2) = emitRefOut(manifestResources2, name); AssertEx.NotEqual(image1, image2, message: "Expecting different main assemblies produced by refout"); AssertEx.Equal(metadataImage1, metadataImage2, message: "Expecting identical ref assemblies produced by refout"); var refAssembly1 = Assembly.ReflectionOnlyLoad(metadataImage1.ToArray()); Assert.DoesNotContain("A", refAssembly1.GetManifestResourceNames()); // Verify refonly string name2 = GetUniqueName(); var refOnlyMetadataImage1 = emitRefOnly(manifestResources1, name2); var refOnlyMetadataImage2 = emitRefOnly(manifestResources2, name2); AssertEx.Equal(refOnlyMetadataImage1, refOnlyMetadataImage2, message: "Expecting identical ref assemblies produced by refonly"); var refOnlyAssembly1 = Assembly.ReflectionOnlyLoad(refOnlyMetadataImage1.ToArray()); Assert.DoesNotContain("A", refOnlyAssembly1.GetManifestResourceNames()); } (ImmutableArray<byte>, ImmutableArray<byte>) emitRefOut(IEnumerable<ResourceDescription> manifestResources, string name) { var source = Parse(""); var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); comp.VerifyDiagnostics(); var metadataPEStream = new MemoryStream(); var refoutOptions = EmitOptions.Default.WithEmitMetadataOnly(false).WithIncludePrivateMembers(false); var peStream = comp.EmitToArray(refoutOptions, metadataPEStream: metadataPEStream, manifestResources: manifestResources); return (peStream, metadataPEStream.ToImmutable()); } ImmutableArray<byte> emitRefOnly(IEnumerable<ResourceDescription> manifestResources, string name) { var source = Parse(""); var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); comp.VerifyDiagnostics(); var refonlyOptions = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); return comp.EmitToArray(refonlyOptions, metadataPEStream: null, manifestResources: manifestResources); } } #endif [Fact, WorkItem(31197, "https://github.com/dotnet/roslyn/issues/31197")] public void RefAssembly_CryptoHashFailedIsOnlyReportedOnce() { var hash_resources = new[] {new ResourceDescription("hash_resource", "snKey.snk", () => new MemoryStream(TestResources.General.snKey, writable: false), true)}; CSharpCompilation moduleComp = CreateEmptyCompilation("", options: TestOptions.DebugDll.WithDeterministic(true).WithOutputKind(OutputKind.NetModule)); var reference = ModuleMetadata.CreateFromImage(moduleComp.EmitToArray()).GetReference(); CSharpCompilation compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M() {} } ", references: new[] { reference }, options: TestOptions.ReleaseDll); // refonly var refonlyOptions = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); var refonlyDiagnostics = compilation.Emit(new MemoryStream(), pdbStream: null, options: refonlyOptions, manifestResources: hash_resources).Diagnostics; refonlyDiagnostics.Verify( // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); // refout var refoutOptions = EmitOptions.Default.WithEmitMetadataOnly(false).WithIncludePrivateMembers(false); var refoutDiagnostics = compilation.Emit(peStream: new MemoryStream(), metadataPEStream: new MemoryStream(), pdbStream: null, options: refoutOptions, manifestResources: hash_resources).Diagnostics; refoutDiagnostics.Verify( // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); } [Fact] public void RefAssemblyClient_RefReadonlyParameters() { VerifyRefAssemblyClient(@" public class C { public void RR_input(in int x) => throw null; public ref readonly int RR_output() => throw null; public ref readonly int P => throw null; public ref readonly int this[in int i] => throw null; public delegate ref readonly int Delegate(in int i); } public static class Extensions { public static void RR_extension(in this int x) => throw null; public static void R_extension(ref this int x) => throw null; }", @"class D { void M(C c, in int y) { c.RR_input(y); VerifyRR(c.RR_output()); VerifyRR(c.P); VerifyRR(c[y]); C.Delegate x = VerifyDelegate; y.RR_extension(); 1.RR_extension(); y.R_extension(); // error 1 1.R_extension(); // error 2 } void VerifyRR(in int y) => throw null; ref readonly int VerifyDelegate(in int y) => throw null; }", comp => comp.VerifyDiagnostics( // (12,9): error CS8329: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // y.R_extension(); // error 1 Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "y").WithArguments("variable", "in int").WithLocation(12, 9), // (13,9): error CS1510: A ref or out value must be an assignable variable // 1.R_extension(); // error 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(13, 9) )); } [Fact] public void RefAssemblyClient_StructWithPrivateReferenceTypeField() { VerifyRefAssemblyClient(@" public struct S { private object _field; public static S GetValue() => new S() { _field = new object() }; public object GetField() => _field; }", @"class C { void M() { unsafe { System.Console.WriteLine(sizeof(S*)); } } }", comp => comp.VerifyDiagnostics( // (7,45): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // System.Console.WriteLine(sizeof(S*)); Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S").WithLocation(7, 45) )); } [Fact] public void RefAssemblyClient_ExplicitPropertyImplementation() { VerifyRefAssemblyClient(@" public interface I { int P { get; set; } } public class Base : I { int I.P { get { throw null; } set { throw null; } } }", @" class Derived : Base, I { }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitAllNestedTypes() { VerifyRefAssemblyClient(@" public interface I1<T> { } public interface I2 { } public class A: I1<A.X> { private class X: I2 { } }", @"class C { I1<I2> M(A a) { return (I1<I2>)a; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitTupleNames() { VerifyRefAssemblyClient(@" public class A { public (int first, int) field; }", @"class C { void M(A a) { System.Console.Write(a.field.first); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitDynamic() { VerifyRefAssemblyClient(@" public class A { public dynamic field; }", @"class C { void M(A a) { System.Console.Write(a.field.DynamicMethod()); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitOut() { VerifyRefAssemblyClient(@" public class A { public void M(out int x) { x = 1; } }", @"class C { void M(A a) { a.M(out int x); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitVariance_OutError() { VerifyRefAssemblyClient(@" public interface I<out T> { }", @" class Base { } class Derived : Base { I<Derived> M(I<Base> x) { return x; } }", comp => comp.VerifyDiagnostics( // (7,16): error CS0266: Cannot implicitly convert type 'I<Base>' to 'I<Derived>'. An explicit conversion exists (are you missing a cast?) // return x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("I<Base>", "I<Derived>").WithLocation(7, 16) )); } [Fact] public void RefAssemblyClient_EmitVariance_OutSuccess() { VerifyRefAssemblyClient(@" public interface I<out T> { }", @" class Base { } class Derived : Base { I<Base> M(I<Derived> x) { return x; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitVariance_InSuccess() { VerifyRefAssemblyClient(@" public interface I<in T> { }", @" class Base { } class Derived : Base { I<Derived> M(I<Base> x) { return x; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitVariance_InError() { VerifyRefAssemblyClient(@" public interface I<in T> { }", @" class Base { } class Derived : Base { I<Base> M(I<Derived> x) { return x; } }", comp => comp.VerifyDiagnostics( // (7,16): error CS0266: Cannot implicitly convert type 'I<Derived>' to 'I<Base>'. An explicit conversion exists (are you missing a cast?) // return x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("I<Derived>", "I<Base>").WithLocation(7, 16) )); } [Fact] public void RefAssemblyClient_EmitOptionalArguments() { VerifyRefAssemblyClient(@" public class A { public void M(int x = 42) { } }", @" class C { void M2(A a) { a.M(); } }", comp => { comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M2", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: nop IL_0001: ldarg.1 IL_0002: ldc.i4.s 42 IL_0004: callvirt ""void A.M(int)"" IL_0009: nop IL_000a: ret }"); }); } [Fact] public void RefAssemblyClient_EmitArgumentNames() { VerifyRefAssemblyClient(@" public class Base { public virtual void M(int x) { } } public class Derived : Base { public override void M(int different) { } }", @" class C { void M2(Derived d) { d.M(different: 1); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitEnum() { VerifyRefAssemblyClient(@" public enum E { Default, Other }", @" class C { void M2(E e) { System.Console.Write(E.Other); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitConst() { VerifyRefAssemblyClient(@" public class A { public const int number = 42; }", @" class C { void M2() { System.Console.Write(A.number); } }", comp => { comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M2", @" { // Code size 10 (0xa) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: call ""void System.Console.Write(int)"" IL_0008: nop IL_0009: ret }"); }); } [Fact] public void RefAssemblyClient_EmitParams() { VerifyRefAssemblyClient(@" public class A { public void M(params int[] x) { } }", @" class C { void M2(A a) { a.M(1, 2, 3); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitExtension() { VerifyRefAssemblyClient(@" public static class A { public static void M(this string x) { } }", @" class C { void M2(string s) { s.M(); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitAllTypes() { VerifyRefAssemblyClient(@" public interface I1<T> { } public interface I2 { } public class A: I1<X> { } internal class X: I2 { } ", @"class C { I1<I2> M(A a) { return (I1<I2>)a; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitNestedTypes() { VerifyRefAssemblyClient(@" public class A { public class Nested { } } ", @"class C { void M(A.Nested a) { } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_StructWithPrivateGenericField() { VerifyRefAssemblyClient(@" public struct Container<T> { private T contained; public void SetField(T value) { contained = value; } public T GetField() => contained; }", @"public struct Usage { public Container<Usage> x; }", comp => comp.VerifyDiagnostics( // (3,29): error CS0523: Struct member 'Usage.x' of type 'Container<Usage>' causes a cycle in the struct layout // public Container<Usage> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("Usage.x", "Container<Usage>").WithLocation(3, 29) )); } [Fact] public void RefAssemblyClient_EmitAllVirtualMethods() { var comp1 = CreateCSharpCompilation("CS1", @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS3"")] public abstract class C1 { internal abstract void M(); }", referencedAssemblies: new[] { MscorlibRef }); comp1.VerifyDiagnostics(); var image1 = comp1.EmitToImageReference(EmitOptions.Default); var comp2 = CreateCSharpCompilation("CS2", @"public abstract class C2 : C1 { internal override void M() { } }", referencedAssemblies: new[] { MscorlibRef, image1 }); var image2 = comp2.EmitToImageReference(EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)); // If internal virtual methods were not included in ref assemblies, then C3 could not be concrete and would report // error CS0534: 'C3' does not implement inherited abstract member 'C1.M()' var comp3 = CreateCSharpCompilation("CS3", @"public class C3 : C2 { }", referencedAssemblies: new[] { MscorlibRef, image1, image2 }); comp3.VerifyDiagnostics(); } [Fact] public void RefAssemblyClient_StructWithPrivateIntField() { VerifyRefAssemblyClient(@" public struct S { private int i; private void M() { System.Console.Write(i++); } }", @"class C { string M() { S s; return s.ToString(); } }", comp => comp.VerifyDiagnostics( // (6,16): error CS0165: Use of unassigned local variable 's' // return s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(6, 16) )); } /// <summary> /// The client compilation should not be affected (except for some diagnostic differences) /// by the library assembly only having metadata, or not including private members. /// </summary> private void VerifyRefAssemblyClient(string lib_cs, string client_cs, Action<CSharpCompilation> validator, int debugFlag = -1) { // Whether the library is compiled in full, as metadata-only, or as a ref assembly should be transparent // to the client and the validator should be able to verify the same expectations. if (debugFlag == -1 || debugFlag == 0) { VerifyRefAssemblyClient(lib_cs, client_cs, validator, EmitOptions.Default.WithEmitMetadataOnly(false)); } if (debugFlag == -1 || debugFlag == 1) { VerifyRefAssemblyClient(lib_cs, client_cs, validator, EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(true)); } if (debugFlag == -1 || debugFlag == 2) { VerifyRefAssemblyClient(lib_cs, client_cs, validator, EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)); } } private static void VerifyRefAssemblyClient(string lib_cs, string source, Action<CSharpCompilation> validator, EmitOptions emitOptions) { string name = GetUniqueName(); var libComp = CreateCompilation(lib_cs, options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); libComp.VerifyDiagnostics(); var libImage = libComp.EmitToImageReference(emitOptions); var comp = CreateCompilation(source, references: new[] { libImage }, options: TestOptions.DebugDll.WithAllowUnsafe(true)); validator(comp); } [Theory] [InlineData("", false)] [InlineData(@"[assembly: System.Reflection.AssemblyVersion(""1"")]", false)] [InlineData(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]", true)] public void RefAssembly_EmitAsDeterministic(string source, bool hasWildcard) { var name = GetUniqueName(); var options = TestOptions.DebugDll.WithDeterministic(false); var comp1 = CreateCompilation(source, options: options, assemblyName: name); var (out1, refOut1) = EmitRefOut(comp1); var refOnly1 = EmitRefOnly(comp1); VerifyIdentitiesMatch(out1, refOut1); VerifyIdentitiesMatch(out1, refOnly1); AssertEx.Equal(refOut1, refOut1); // The resolution of the PE header time date stamp is seconds (divided by two), and we want to make sure that has an opportunity to change // between calls to Emit. Thread.Sleep(TimeSpan.FromSeconds(3)); // Re-using the same compilation results in the same time stamp var (out15, refOut15) = EmitRefOut(comp1); VerifyIdentitiesMatch(out1, out15); VerifyIdentitiesMatch(refOut1, refOut15); AssertEx.Equal(refOut1, refOut15); // Using a new compilation results in new time stamp var comp2 = CreateCompilation(source, options: options, assemblyName: name); var (out2, refOut2) = EmitRefOut(comp2); var refOnly2 = EmitRefOnly(comp2); VerifyIdentitiesMatch(out2, refOut2); VerifyIdentitiesMatch(out2, refOnly2); VerifyIdentitiesMatch(out1, out2, expectMatch: !hasWildcard); VerifyIdentitiesMatch(refOut1, refOut2, expectMatch: !hasWildcard); if (hasWildcard) { AssertEx.NotEqual(refOut1, refOut2); AssertEx.NotEqual(refOut1, refOnly2); } else { // If no wildcards, the binaries are emitted deterministically AssertEx.Equal(refOut1, refOut2); AssertEx.Equal(refOut1, refOnly2); } } private void VerifySigned(ImmutableArray<byte> image, bool expectSigned = true) { using (var reader = new PEReader(image)) { var flags = reader.PEHeaders.CorHeader.Flags; Assert.Equal(expectSigned, flags.HasFlag(CorFlags.StrongNameSigned)); } } private static void VerifyIdentitiesMatch(ImmutableArray<byte> firstImage, ImmutableArray<byte> secondImage, bool expectMatch = true, bool expectPublicKey = false) { var id1 = ModuleMetadata.CreateFromImage(firstImage).GetMetadataReader().ReadAssemblyIdentityOrThrow(); var id2 = ModuleMetadata.CreateFromImage(secondImage).GetMetadataReader().ReadAssemblyIdentityOrThrow(); Assert.Equal(expectMatch, id1 == id2); if (expectPublicKey) { Assert.True(id1.HasPublicKey); Assert.True(id2.HasPublicKey); } } private static (ImmutableArray<byte> image, ImmutableArray<byte> refImage) EmitRefOut(CSharpCompilation comp) { using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { var options = EmitOptions.Default.WithIncludePrivateMembers(false); comp.VerifyEmitDiagnostics(); var result = comp.Emit(output, metadataPEStream: metadataOutput, options: options); return (output.ToImmutable(), metadataOutput.ToImmutable()); } } private static ImmutableArray<byte> EmitRefOnly(CSharpCompilation comp) { using (var output = new MemoryStream()) { var options = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); comp.VerifyEmitDiagnostics(); var result = comp.Emit(output, options: options); return output.ToImmutable(); } } [Fact] public void RefAssembly_PublicSigning() { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C{}", options: TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(true)); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image); VerifySigned(refImage); VerifySigned(refOnlyImage); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Fact] public void RefAssembly_StrongNameProvider() { var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile); var comp = CreateCompilation("public class C{}", options: signedDllOptions); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image); VerifySigned(refImage); VerifySigned(refOnlyImage); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Fact] public void RefAssembly_StrongNameProvider_Arm64() { var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile). WithPlatform(Platform.Arm64). WithDeterministic(true); var comp = CreateCompilation("public class C{}", options: signedDllOptions); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image); VerifySigned(refImage); VerifySigned(refOnlyImage); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Fact] public void RefAssembly_StrongNameProviderAndDelaySign() { var signedDllOptions = TestOptions.SigningReleaseDll .WithCryptoKeyFile(SigningTestHelpers.KeyPairFile) .WithDelaySign(true); var comp = CreateCompilation("public class C{}", options: signedDllOptions); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image, expectSigned: false); VerifySigned(refImage, expectSigned: false); VerifySigned(refOnlyImage, expectSigned: false); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Theory] [InlineData("public int M() { error(); }", true)] [InlineData("public int M() { error() }", false)] // This may get relaxed. See follow-up issue https://github.com/dotnet/roslyn/issues/17612 [InlineData("public int M();", true)] [InlineData("public int M() { int Local(); }", true)] [InlineData("public C();", true)] [InlineData("~ C();", true)] [InlineData("public Error M() { return null; }", false)] // This may get relaxed. See follow-up issue https://github.com/dotnet/roslyn/issues/17612 [InlineData("public static explicit operator C(int i);", true)] [InlineData("public async Task M();", false)] [InlineData("partial void M(); partial void M();", false)] // This may get relaxed. See follow-up issue https://github.com/dotnet/roslyn/issues/17612 public void RefAssembly_IgnoresSomeDiagnostics(string change, bool expectSuccess) { string sourceTemplate = @" using System.Threading.Tasks; public partial class C { CHANGE } "; VerifyIgnoresDiagnostics(EmitOptions.Default.WithEmitMetadataOnly(false).WithTolerateErrors(false), success: false); VerifyIgnoresDiagnostics(EmitOptions.Default.WithEmitMetadataOnly(true).WithTolerateErrors(false), success: expectSuccess); void VerifyIgnoresDiagnostics(EmitOptions emitOptions, bool success) { string source = sourceTemplate.Replace("CHANGE", change); string name = GetUniqueName(); CSharpCompilation comp = CreateCompilation(Parse(source), options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); using (var output = new MemoryStream()) { var emitResult = comp.Emit(output, options: emitOptions); Assert.Equal(!success, emitResult.Diagnostics.HasAnyErrors()); Assert.Equal(success, emitResult.Success); } } } [Fact] public void RefAssembly_VerifyTypesAndMembers() { string source = @" public class PublicClass { public void PublicMethod() { System.Console.Write(new { anonymous = 1 }); } private void PrivateMethod() { System.Console.Write(""Hello""); } protected void ProtectedMethod() { System.Console.Write(""Hello""); } internal void InternalMethod() { System.Console.Write(""Hello""); } protected internal void ProtectedInternalMethod() { } private protected void PrivateProtectedMethod() { } public event System.Action PublicEvent; internal event System.Action InternalEvent; } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, parseOptions: TestOptions.Regular7_2, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "<>f__AnonymousType0<<anonymous>j__TPar>", "PublicClass" }, compWithReal.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.PrivateMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.InternalMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PrivateProtectedMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "void PublicClass.InternalEvent.add", "void PublicClass.InternalEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent", "event System.Action PublicClass.InternalEvent" }, compWithReal.GetMember<NamedTypeSymbol>("PublicClass").GetMembers() .Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute" }, compWithReal.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); // Verify metadata (types, members, attributes) of the regular assembly with IncludePrivateMembers accidentally set to false. // Note this can happen because of binary clients compiled against old EmitOptions ctor which had IncludePrivateMembers=false by default. // In this case, IncludePrivateMembers is silently set to true when emitting // See https://github.com/dotnet/roslyn/issues/20873 var emitRegularWithoutPrivateMembers = EmitOptions.Default.WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRegularWithoutPrivateMembers, verify: Verification.Passes); var realImage2 = comp.EmitToImageReference(emitRegularWithoutPrivateMembers); var compWithReal2 = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage2 }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "<>f__AnonymousType0<<anonymous>j__TPar>", "PublicClass" }, compWithReal2.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.PrivateMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.InternalMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PrivateProtectedMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "void PublicClass.InternalEvent.add", "void PublicClass.InternalEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent", "event System.Action PublicClass.InternalEvent" }, compWithReal2.GetMember<NamedTypeSymbol>("PublicClass").GetMembers() .Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute" }, compWithReal2.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "PublicClass" }, compWithMetadata.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.PrivateMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.InternalMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PrivateProtectedMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "void PublicClass.InternalEvent.add", "void PublicClass.InternalEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent", "event System.Action PublicClass.InternalEvent" }, compWithMetadata.GetMember<NamedTypeSymbol>("PublicClass").GetMembers().Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute" }, compWithMetadata.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "PublicClass" }, compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent"}, compWithRef.GetMember<NamedTypeSymbol>("PublicClass").GetMembers().Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute", "System.Runtime.CompilerServices.ReferenceAssemblyAttribute" }, compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); } [Fact] public void RefAssembly_VerifyTypesAndMembersOnExplicitlyImplementedProperty() { string source = @" public interface I { int P { get; set; } } public class C : I { int I.P { get { throw null; } set { throw null; } } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyPropertyWasEmitted(compWithReal); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyPropertyWasEmitted(compWithMetadata); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyPropertyWasEmitted(compWithRef); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); void verifyPropertyWasEmitted(CSharpCompilation input) { AssertEx.Equal( new[] { "<Module>", "I", "C" }, input.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Int32 C.I.P.get", "void C.I.P.set", "C..ctor()", "System.Int32 C.I.P { get; set; }" }, input.GetMember<NamedTypeSymbol>("C").GetMembers() .Select(m => m.ToTestDisplayString())); } } [Fact] public void RefAssembly_VerifyTypesAndMembersOnExplicitlyImplementedEvent() { string source = @" public interface I { event System.Action E; } public class C : I { event System.Action I.E { add { throw null; } remove { throw null; } } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyEventWasEmitted(compWithReal); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyEventWasEmitted(compWithMetadata); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyEventWasEmitted(compWithRef); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); void verifyEventWasEmitted(CSharpCompilation input) { AssertEx.Equal( new[] { "<Module>", "I", "C" }, input.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void C.I.E.add", "void C.I.E.remove", "C..ctor()", "event System.Action C.I.E" }, input.GetMember<NamedTypeSymbol>("C").GetMembers() .Select(m => m.ToTestDisplayString())); } } [Fact] public void RefAssembly_VerifyTypesAndMembersOnExplicitlyImplementedIndexer() { string source = @" public interface I { int this[int i] { get; set; } } public class C : I { int I.this[int i] { get { throw null; } set { throw null; } } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyIndexerWasEmitted(compWithReal); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyIndexerWasEmitted(compWithMetadata); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyIndexerWasEmitted(compWithRef); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); void verifyIndexerWasEmitted(CSharpCompilation input) { AssertEx.Equal( new[] { "<Module>", "I", "C" }, input.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] {"System.Int32 C.I.get_Item(System.Int32 i)", "void C.I.set_Item(System.Int32 i, System.Int32 value)", "C..ctor()", "System.Int32 C.I.Item[System.Int32 i] { get; set; }" }, input.GetMember<NamedTypeSymbol>("C").GetMembers() .Select(m => m.ToTestDisplayString())); } } [Fact] public void RefAssembly_VerifyTypesAndMembersOnStruct() { string source = @" internal struct InternalStruct { internal int P { get; set; } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var globalNamespace = compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace; AssertEx.Equal( new[] { "<Module>", "InternalStruct", "Microsoft", "System" }, globalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal(new[] { "Microsoft.CodeAnalysis" }, globalNamespace.GetMember<NamespaceSymbol>("Microsoft").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "Microsoft.CodeAnalysis.EmbeddedAttribute" }, globalNamespace.GetMember<NamespaceSymbol>("Microsoft.CodeAnalysis").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices" }, globalNamespace.GetMember<NamespaceSymbol>("System.Runtime").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.IsReadOnlyAttribute" }, globalNamespace.GetMember<NamespaceSymbol>("System.Runtime.CompilerServices").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Int32 InternalStruct.<P>k__BackingField", "InternalStruct..ctor()" }, compWithRef.GetMember<NamedTypeSymbol>("InternalStruct").GetMembers().Select(m => m.ToTestDisplayString())); } [Fact] public void RefAssembly_VerifyTypesAndMembersOnPrivateStruct() { string source = @" struct S { private class PrivateType { } private PrivateType field; } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "S" }, compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "S.PrivateType S.field", "S..ctor()", "S.PrivateType" }, compWithRef.GetMember<NamedTypeSymbol>("S").GetMembers().Select(m => m.ToTestDisplayString())); } [Fact] public void EmitMetadataOnly_DisallowPdbs() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var pdbOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, pdbOutput, options: EmitOptions.Default.WithEmitMetadataOnly(true))); } } [Fact] public void EmitMetadataOnly_DisallowMetadataPeStream() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var metadataPeOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, metadataPEStream: metadataPeOutput, options: EmitOptions.Default.WithEmitMetadataOnly(true))); } } [Fact] public void IncludePrivateMembers_DisallowMetadataPeStream() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var metadataPeOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, metadataPEStream: metadataPeOutput, options: EmitOptions.Default.WithIncludePrivateMembers(true))); } } [Fact] [WorkItem(20873, "https://github.com/dotnet/roslyn/issues/20873")] public void IncludePrivateMembersSilentlyAssumedTrueWhenEmittingRegular() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) { // no exception _ = comp.Emit(output, options: EmitOptions.Default.WithIncludePrivateMembers(false)); } } [Fact] public void EmitMetadata_DisallowOutputtingNetModule() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true).WithOutputKind(OutputKind.NetModule)); using (var output = new MemoryStream()) using (var metadataPeOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, metadataPEStream: metadataPeOutput, options: EmitOptions.Default)); } } [Fact] public void EmitMetadataOnly_DisallowOutputtingNetModule() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true).WithOutputKind(OutputKind.NetModule)); using (var output = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, options: EmitOptions.Default.WithEmitMetadataOnly(true))); } } [Fact] public void RefAssembly_AllowEmbeddingPdb() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { var result = comp.Emit(output, metadataPEStream: metadataOutput, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded).WithIncludePrivateMembers(false)); VerifyEmbeddedDebugInfo(output, new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }); VerifyEmbeddedDebugInfo(metadataOutput, new DebugDirectoryEntryType[] { DebugDirectoryEntryType.Reproducible }); } void VerifyEmbeddedDebugInfo(MemoryStream stream, DebugDirectoryEntryType[] expected) { using (var peReader = new PEReader(stream.ToImmutable())) { var entries = peReader.ReadDebugDirectory(); AssertEx.Equal(expected, entries.Select(e => e.Type)); } } } [Fact] public void EmitMetadataOnly_DisallowEmbeddingPdb() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll); using (var output = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, options: EmitOptions.Default.WithEmitMetadataOnly(true) .WithDebugInformationFormat(DebugInformationFormat.Embedded))); } } [Fact] public void EmitMetadata() { string source = @" public abstract class PublicClass { public void PublicMethod() { System.Console.Write(""Hello""); } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var pdbOutput = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { var result = comp.Emit(output, pdbOutput, metadataPEStream: metadataOutput); Assert.True(result.Success); Assert.NotEqual(0, output.Position); Assert.NotEqual(0, pdbOutput.Position); Assert.NotEqual(0, metadataOutput.Position); MetadataReaderUtils.AssertNotThrowNull(ImmutableArray.CreateRange(output.GetBuffer())); MetadataReaderUtils.AssertEmptyOrThrowNull(ImmutableArray.CreateRange(metadataOutput.GetBuffer())); } var peImage = comp.EmitToArray(); MetadataReaderUtils.AssertNotThrowNull(peImage); } /// <summary> /// Check that when we emit metadata only, we include metadata for /// compiler generate methods (e.g. the ones for implicit interface /// implementation). /// </summary> [Fact] public void EmitMetadataOnly_SynthesizedExplicitImplementations() { var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll; var libAssemblyName = "SynthesizedMethodMetadata"; var exeAssemblyName = "CallSynthesizedMethod"; // Setup: CppBase2 has methods that implement CppInterface1, but it doesn't declare // that it implements the interface. Class1 does declare that it implements the // interface, but it's empty so it counts on CppBase2 to provide the implementations. // Since CppBase2 is not in the current source module, bridge methods are inserted // into Class1 to implement the interface methods by delegating to CppBase2. var libText = @" public class Class1 : CppCli.CppBase2, CppCli.CppInterface1 { } "; var libComp = CreateCompilation( source: libText, references: new MetadataReference[] { ilAssemblyReference }, options: TestOptions.ReleaseDll, assemblyName: libAssemblyName); Assert.False(libComp.GetDiagnostics().Any()); EmitResult emitResult; byte[] dllImage; using (var output = new MemoryStream()) { emitResult = libComp.Emit(output, options: new EmitOptions(metadataOnly: true)); dllImage = output.ToArray(); } Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); Assert.True(dllImage.Length > 0, "no metadata emitted"); // NOTE: this DLL won't PEVerify because there are no method bodies. var class1 = libComp.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("Class1"); // We would prefer to check that the module used by Compiler.Emit does the right thing, // but we don't have access to that object, so we'll create our own and manipulate it // in the same way. var module = new PEAssemblyBuilder((SourceAssemblySymbol)class1.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); SynthesizedMetadataCompiler.ProcessSynthesizedMembers(libComp, module, default(CancellationToken)); var class1TypeDef = (Cci.ITypeDefinition)class1.GetCciAdapter(); var symbolSynthesized = class1.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods; var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var cciExplicit = class1TypeDef.GetExplicitImplementationOverrides(context); var cciMethods = class1TypeDef.GetMethods(context).Where(m => ((MethodSymbol)m.GetInternalSymbol()).MethodKind != MethodKind.Constructor); context.Diagnostics.Verify(); var symbolsSynthesizedCount = symbolSynthesized.Length; Assert.True(symbolsSynthesizedCount > 0, "Expected more than 0 synthesized method symbols."); Assert.Equal(symbolsSynthesizedCount, cciExplicit.Count()); Assert.Equal(symbolsSynthesizedCount, cciMethods.Count()); var libAssemblyReference = MetadataReference.CreateFromImage(dllImage.AsImmutableOrNull()); var exeText = @" class Class2 { public static void Main() { CppCli.CppInterface1 c = new Class1(); c.Method1(1); c.Method2(2); } } "; var exeComp = CreateCompilation( source: exeText, references: new MetadataReference[] { ilAssemblyReference, libAssemblyReference }, assemblyName: exeAssemblyName); Assert.False(exeComp.GetDiagnostics().Any()); using (var output = new MemoryStream()) { emitResult = exeComp.Emit(output); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); output.Flush(); Assert.True(output.Length > 0, "no metadata emitted"); } // NOTE: there's no point in trying to run the EXE since it depends on a DLL with no method bodies. } [WorkItem(539982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539982")] [Fact] public void EmitNestedLambdaWithAddPlusOperator() { CompileAndVerify(@" public class C { delegate int D(int i); delegate D E(int i); public static void Main() { D y = x => x + 1; E e = x => (y += (z => z + 1)); } } "); } [Fact, WorkItem(539983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539983")] public void EmitAlwaysFalseExpression() { CompileAndVerify(@" class C { static bool Goo(int i) { int y = 10; bool x = (y == null); // NYI: Implicit null conversion return x; } } "); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void EmitLambdaInConstructorInitializer() { string source = @" using System; public class A { public A(string x):this(()=>x) {} public A(Func<string> x) { Console.WriteLine(x()); } static void Main() { A a = new A(""Hello""); } }"; CompileAndVerify(source, expectedOutput: "Hello"); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void EmitLambdaInConstructorBody() { string source = @" using System; public class A { public string y = ""!""; public A(string x) {func(()=>x+y); } public A(Func<string> x) { Console.WriteLine(x()); } public void func(Func<string> x) { Console.WriteLine(x()); } static void Main() { A a = new A(""Hello""); } }"; CompileAndVerify(source, expectedOutput: "Hello!"); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void EmitLambdaInConstructorInitializerAndBody() { string source = @" using System; public class A { public string y = ""!""; public A(string x):this(()=>x){func(()=>x+y);} public A(Func<string> x) { Console.WriteLine(x()); } public void func (Func<string> x) { Console.WriteLine(x()); } static void Main() { A a = new A(""Hello""); } }"; CompileAndVerify(source, expectedOutput: @" Hello Hello! "); } [WorkItem(541786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541786")] [Fact] public void EmitInvocationExprInIfStatementNestedInsideCatch() { string source = @" static class Test { static public void Main() { int i1 = 45; try { } catch { if (i1.ToString() == null) { } } System.Console.WriteLine(i1); } }"; CompileAndVerify(source, expectedOutput: "45"); } [WorkItem(541822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541822")] [Fact] public void EmitSwitchOnByteType() { string source = @" using System; public class Test { public static object TestSwitch(byte val) { switch (val) { case (byte)0: return 0; case (byte)1: return 1; case (byte)0x7F: return (byte)0x7F; case (byte)0xFE: return (byte)0xFE; case (byte)0xFF: return (byte)0xFF; default: return null; } } public static void Main() { Console.WriteLine(TestSwitch(0)); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541823")] [Fact] public void EmitSwitchOnIntTypeBoundary() { string source = @" public class Test { public static object TestSwitch(int val) { switch (val) { case (int)int.MinValue: case (int)int.MinValue + 1: case (int)short.MinValue: case (int)short.MinValue + 1: case (int)sbyte.MinValue: return 0; case (int)-1: return -1; case (int)0: return 0; case (int)1: return 0; case (int)0x7F: return 0; case (int)0xFE: return 0; case (int)0xFF: return 0; case (int)0x7FFE: return 0; case (int)0xFFFE: case (int)0x7FFFFFFF: return 0; default: return null; } } public static void Main() { System.Console.WriteLine(TestSwitch(-1)); } } "; CompileAndVerify(source, expectedOutput: "-1"); } [WorkItem(541824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541824")] [Fact] public void EmitSwitchOnLongTypeBoundary() { string source = @" public class Test { public static object TestSwitch(long val) { switch (val) { case (long)long.MinValue: return (long)long.MinValue; case (long)long.MinValue + 1: return (long)long.MinValue + 1; case (long)int.MinValue: return (long)int.MinValue; case (long)int.MinValue + 1: return (long)int.MinValue + 1; case (long)short.MinValue: return (long)short.MinValue; case (long)short.MinValue + 1: return (long)short.MinValue + 1; case (long)sbyte.MinValue: return (long)sbyte.MinValue; case (long)-1: return (long)-1; case (long)0: return (long)0; case (long)1: return (long)1; case (long)0x7F: return (long)0x7F; case (long)0xFE: return (long)0xFE; case (long)0xFF: return (long)0xFF; case (long)0x7FFE: return (long)0x7FFE; case (long)0x7FFF: return (long)0x7FFF; case (long)0xFFFE: return (long)0xFFFE; case (long)0xFFFF: return (long)0xFFFF; case (long)0x7FFFFFFE: return (long)0x7FFFFFFE; case (long)0x7FFFFFFF: return (long)0x7FFFFFFF; case (long)0xFFFFFFFE: return (long)0xFFFFFFFE; case (long)0xFFFFFFFF: return (long)0xFFFFFFFF; case (long)0x7FFFFFFFFFFFFFFE: return (long)0x7FFFFFFFFFFFFFFE; case (long)0x7FFFFFFFFFFFFFFF: return (long)0x7FFFFFFFFFFFFFFF; default: return null; } } public static void Main() { System.Console.WriteLine(TestSwitch(0)); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnLongTypeBoundary2() { string source = @" public class Test { private static int DoLong() { int ret = 2; long l = 0x7fffffffffffffffL; switch (l) { case 1L: case 9223372036854775807L: ret--; break; case -1L: break; default: break; } switch (l) { case 1L: case -1L: break; default: ret--; break; } return (ret); } public static void Main(string[] args) { System.Console.WriteLine(DoLong()); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnLongTypeBoundary3() { string source = @" public class Test { public static object TestSwitch(long val) { switch (val) { case (long)long.MinValue: return (long)long.MinValue; case (long)long.MinValue + 1: return (long)long.MinValue + 1; case (long)int.MinValue: return (long)int.MinValue; case (long)int.MinValue + 1: return (long)int.MinValue + 1; case (long)short.MinValue: return (long)short.MinValue; case (long)short.MinValue + 1: return (long)short.MinValue + 1; case (long)sbyte.MinValue: return (long)sbyte.MinValue; case (long)-1: return (long)-1; case (long)0: return (long)0; case (long)1: return (long)1; case (long)0x7F: return (long)0x7F; case (long)0xFE: return (long)0xFE; case (long)0xFF: return (long)0xFF; case (long)0x7FFE: return (long)0x7FFE; case (long)0x7FFF: return (long)0x7FFF; case (long)0xFFFE: return (long)0xFFFE; case (long)0xFFFF: return (long)0xFFFF; case (long)0x7FFFFFFE: return (long)0x7FFFFFFE; case (long)0x7FFFFFFF: return (long)0x7FFFFFFF; case (long)0xFFFFFFFE: return (long)0xFFFFFFFE; case (long)0xFFFFFFFF: return (long)0xFFFFFFFF; case (long)0x7FFFFFFFFFFFFFFE: return (long)0x7FFFFFFFFFFFFFFE; case (long)0x7FFFFFFFFFFFFFFF: return (long)0x7FFFFFFFFFFFFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((long)long.MinValue).Equals(TestSwitch(long.MinValue))); b1 = b1 && (((long)long.MinValue + 1).Equals(TestSwitch(long.MinValue + 1))); b1 = b1 && (((long)int.MinValue).Equals(TestSwitch(int.MinValue))); b1 = b1 && (((long)int.MinValue + 1).Equals(TestSwitch(int.MinValue + 1))); b1 = b1 && (((long)short.MinValue).Equals(TestSwitch(short.MinValue))); b1 = b1 && (((long)short.MinValue + 1).Equals(TestSwitch(short.MinValue + 1))); b1 = b1 && (((long)sbyte.MinValue).Equals(TestSwitch(sbyte.MinValue))); b1 = b1 && (((long)-1).Equals(TestSwitch(-1))); b1 = b1 && (((long)0).Equals(TestSwitch(0))); b1 = b1 && (((long)1).Equals(TestSwitch(1))); b1 = b1 && (((long)0x7F).Equals(TestSwitch(0x7F))); b1 = b1 && (((long)0xFE).Equals(TestSwitch(0xFE))); b1 = b1 && (((long)0xFF).Equals(TestSwitch(0xFF))); b1 = b1 && (((long)0x7FFE).Equals(TestSwitch(0x7FFE))); b1 = b1 && (((long)0x7FFF).Equals(TestSwitch(0x7FFF))); b1 = b1 && (((long)0xFFFE).Equals(TestSwitch(0xFFFE))); b1 = b1 && (((long)0xFFFF).Equals(TestSwitch(0xFFFF))); b1 = b1 && (((long)0x7FFFFFFE).Equals(TestSwitch(0x7FFFFFFE))); b1 = b1 && (((long)0x7FFFFFFF).Equals(TestSwitch(0x7FFFFFFF))); b1 = b1 && (((long)0xFFFFFFFE).Equals(TestSwitch(0xFFFFFFFE))); b1 = b1 && (((long)0xFFFFFFFF).Equals(TestSwitch(0xFFFFFFFF))); b1 = b1 && (((long)0x7FFFFFFFFFFFFFFE).Equals(TestSwitch(0x7FFFFFFFFFFFFFFE))); b1 = b1 && (((long)0x7FFFFFFFFFFFFFFF).Equals(TestSwitch(0x7FFFFFFFFFFFFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnCharTypeBoundary() { string source = @" public class Test { public static object TestSwitch(char val) { switch (val) { case (char)0: return (char)0; case (char)1: return (char)1; case (char)0x7F: return (char)0x7F; case (char)0xFE: return (char)0xFE; case (char)0xFF: return (char)0xFF; case (char)0x7FFE: return (char)0x7FFE; case (char)0x7FFF: return (char)0x7FFF; case (char)0xFFFE: return (char)0xFFFE; case (char)0xFFFF: return (char)0xFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((char)0).Equals(TestSwitch((char)0))); b1 = b1 && (((char)1).Equals(TestSwitch((char)1))); b1 = b1 && (((char)0x7F).Equals(TestSwitch((char)0x7F))); b1 = b1 && (((char)0xFE).Equals(TestSwitch((char)0xFE))); b1 = b1 && (((char)0xFF).Equals(TestSwitch((char)0xFF))); b1 = b1 && (((char)0x7FFE).Equals(TestSwitch((char)0x7FFE))); b1 = b1 && (((char)0x7FFF).Equals(TestSwitch((char)0x7FFF))); b1 = b1 && (((char)0xFFFE).Equals(TestSwitch((char)0xFFFE))); b1 = b1 && (((char)0xFFFF).Equals(TestSwitch((char)0xFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnUIntTypeBoundary() { string source = @" public class Test { public static object TestSwitch(uint val) { switch (val) { case (uint)0: return (uint)0; case (uint)1: return (uint)1; case (uint)0x7F: return (uint)0x7F; case (uint)0xFE: return (uint)0xFE; case (uint)0xFF: return (uint)0xFF; case (uint)0x7FFE: return (uint)0x7FFE; case (uint)0x7FFF: return (uint)0x7FFF; case (uint)0xFFFE: return (uint)0xFFFE; case (uint)0xFFFF: return (uint)0xFFFF; case (uint)0x7FFFFFFE: return (uint)0x7FFFFFFE; case (uint)0x7FFFFFFF: return (uint)0x7FFFFFFF; case (uint)0xFFFFFFFE: return (uint)0xFFFFFFFE; case (uint)0xFFFFFFFF: return (uint)0xFFFFFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((uint)0).Equals(TestSwitch(0))); b1 = b1 && (((uint)1).Equals(TestSwitch(1))); b1 = b1 && (((uint)0x7F).Equals(TestSwitch(0x7F))); b1 = b1 && (((uint)0xFE).Equals(TestSwitch(0xFE))); b1 = b1 && (((uint)0xFF).Equals(TestSwitch(0xFF))); b1 = b1 && (((uint)0x7FFE).Equals(TestSwitch(0x7FFE))); b1 = b1 && (((uint)0x7FFF).Equals(TestSwitch(0x7FFF))); b1 = b1 && (((uint)0xFFFE).Equals(TestSwitch(0xFFFE))); b1 = b1 && (((uint)0xFFFF).Equals(TestSwitch(0xFFFF))); b1 = b1 && (((uint)0x7FFFFFFE).Equals(TestSwitch(0x7FFFFFFE))); b1 = b1 && (((uint)0x7FFFFFFF).Equals(TestSwitch(0x7FFFFFFF))); b1 = b1 && (((uint)0xFFFFFFFE).Equals(TestSwitch(0xFFFFFFFE))); b1 = b1 && (((uint)0xFFFFFFFF).Equals(TestSwitch(0xFFFFFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541824")] [Fact] public void EmitSwitchOnUnsignedLongTypeBoundary() { string source = @" public class Test { public static object TestSwitch(ulong val) { switch (val) { case ulong.MinValue: return 0; case ulong.MaxValue: return 1; default: return 1; } } public static void Main() { System.Console.WriteLine(TestSwitch(0)); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541847, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541847")] [Fact] public void EmitSwitchOnUnsignedLongTypeBoundary2() { string source = @" public class Test { public static object TestSwitch(ulong val) { switch (val) { case (ulong)0: return (ulong)0; case (ulong)1: return (ulong)1; case (ulong)0x7F: return (ulong)0x7F; case (ulong)0xFE: return (ulong)0xFE; case (ulong)0xFF: return (ulong)0xFF; case (ulong)0x7FFE: return (ulong)0x7FFE; case (ulong)0x7FFF: return (ulong)0x7FFF; case (ulong)0xFFFE: return (ulong)0xFFFE; case (ulong)0xFFFF: return (ulong)0xFFFF; case (ulong)0x7FFFFFFE: return (ulong)0x7FFFFFFE; case (ulong)0x7FFFFFFF: return (ulong)0x7FFFFFFF; case (ulong)0xFFFFFFFE: return (ulong)0xFFFFFFFE; case (ulong)0xFFFFFFFF: return (ulong)0xFFFFFFFF; case (ulong)0x7FFFFFFFFFFFFFFE: return (ulong)0x7FFFFFFFFFFFFFFE; case (ulong)0x7FFFFFFFFFFFFFFF: return (ulong)0x7FFFFFFFFFFFFFFF; case (ulong)0xFFFFFFFFFFFFFFFE: return (ulong)0xFFFFFFFFFFFFFFFE; case (ulong)0xFFFFFFFFFFFFFFFF: return (ulong)0xFFFFFFFFFFFFFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((ulong)0).Equals(TestSwitch(0))); b1 = b1 && (((ulong)1).Equals(TestSwitch(1))); b1 = b1 && (((ulong)0x7F).Equals(TestSwitch(0x7F))); b1 = b1 && (((ulong)0xFE).Equals(TestSwitch(0xFE))); b1 = b1 && (((ulong)0xFF).Equals(TestSwitch(0xFF))); b1 = b1 && (((ulong)0x7FFE).Equals(TestSwitch(0x7FFE))); b1 = b1 && (((ulong)0x7FFF).Equals(TestSwitch(0x7FFF))); b1 = b1 && (((ulong)0xFFFE).Equals(TestSwitch(0xFFFE))); b1 = b1 && (((ulong)0xFFFF).Equals(TestSwitch(0xFFFF))); b1 = b1 && (((ulong)0x7FFFFFFE).Equals(TestSwitch(0x7FFFFFFE))); b1 = b1 && (((ulong)0x7FFFFFFF).Equals(TestSwitch(0x7FFFFFFF))); b1 = b1 && (((ulong)0xFFFFFFFE).Equals(TestSwitch(0xFFFFFFFE))); b1 = b1 && (((ulong)0xFFFFFFFF).Equals(TestSwitch(0xFFFFFFFF))); b1 = b1 && (((ulong)0x7FFFFFFFFFFFFFFE).Equals(TestSwitch(0x7FFFFFFFFFFFFFFE))); b1 = b1 && (((ulong)0x7FFFFFFFFFFFFFFF).Equals(TestSwitch(0x7FFFFFFFFFFFFFFF))); b1 = b1 && (((ulong)0xFFFFFFFFFFFFFFFE).Equals(TestSwitch(0xFFFFFFFFFFFFFFFE))); b1 = b1 && (((ulong)0xFFFFFFFFFFFFFFFF).Equals(TestSwitch(0xFFFFFFFFFFFFFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541839")] [Fact] public void EmitSwitchOnShortTypeBoundary() { string source = @" public class Test { public static object TestSwitch(short val) { switch (val) { case (short)short.MinValue: return (short)short.MinValue; case (short)short.MinValue + 1: return (short)short.MinValue + 1; case (short)sbyte.MinValue: return (short)sbyte.MinValue; case (short)-1: return (short)-1; case (short)0: return (short)0; case (short)1: return (short)1; case (short)0x7F: return (short)0x7F; case (short)0xFE: return (short)0xFE; case (short)0xFF: return (short)0xFF; case (short)0x7FFE: return (short)0x7FFE; case (short)0x7FFF: return (short)0x7FFF; default: return null; } } public static void Main() { System.Console.WriteLine(TestSwitch(1)); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542563")] [Fact] public void IncompleteIndexerDeclWithSyntaxErrors() { string source = @" public class Test { public sealed object this"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.False(emitResult.Success); Assert.NotEmpty(emitResult.Diagnostics); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { string source = @" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => i; break; } } }"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.True(emitResult.Success); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void MultipleVariableDeclInsideSwitchCaptureInLambdaExpr() { string source = @" using System; class C { public static void Main() { int i = 0; switch (i) { case 0: int j = 0; Func<int> f1 = () => i + j; break; default: int k = 0; Func<int> f2 = () => i + k; break; } } }"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.True(emitResult.Success); } #region "PE and metadata bits" [Fact] public void CheckRuntimeMDVersion() { string source = @" class C { public static void Main() { } }"; var compilation = CSharpCompilation.Create( "v2Fx.exe", new[] { Parse(source) }, new[] { Net20.mscorlib }); //EDMAURER this is built with a 2.0 mscorlib. The runtimeMetadataVersion should be the same as the runtimeMetadataVersion stored in the assembly //that contains System.Object. var metadataReader = ModuleMetadata.CreateFromStream(compilation.EmitToStream()).MetadataReader; Assert.Equal("v2.0.50727", metadataReader.MetadataVersion); } [Fact] public void CheckCorflags() { string source = @" class C { public static void Main() { } }"; PEHeaders peHeaders; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.AnyCpu)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.Equal(CorFlags.ILOnly, peHeaders.CorHeader.Flags); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.Equal(CorFlags.ILOnly | CorFlags.Requires32Bit, peHeaders.CorHeader.Flags); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.Equal(CorFlags.ILOnly, peHeaders.CorHeader.Flags); Assert.True(peHeaders.Requires64Bits()); Assert.True(peHeaders.RequiresAmdInstructionSet()); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.AnyCpu32BitPreferred)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.False(peHeaders.Requires64Bits()); Assert.False(peHeaders.RequiresAmdInstructionSet()); Assert.Equal(CorFlags.ILOnly | CorFlags.Requires32Bit | CorFlags.Prefers32Bit, peHeaders.CorHeader.Flags); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.Arm)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.False(peHeaders.Requires64Bits()); Assert.False(peHeaders.RequiresAmdInstructionSet()); Assert.Equal(CorFlags.ILOnly, peHeaders.CorHeader.Flags); } [Fact] public void CheckCOFFAndPEOptionalHeaders32() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithPlatform(Platform.X86)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.False(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsDll); Assert.False(peHeaders.IsExe); Assert.False(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); Assert.Equal(0x10000000u, peHeaders.PEHeader.ImageBase); Assert.Equal(0x200, peHeaders.PEHeader.FileAlignment); Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE //Verify additional items Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfHeapCommit); } [Fact] public void CheckCOFFAndPEOptionalHeaders64() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithPlatform(Platform.X64)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.True(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsDll); Assert.False(peHeaders.IsExe); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); // the default value is the same as the 32 bit default value Assert.Equal(0x0000000180000000u, peHeaders.PEHeader.ImageBase); Assert.Equal(0x00000200, peHeaders.PEHeader.FileAlignment); //doesn't change based on architecture. Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE //Verify additional items Assert.Equal(0x00400000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x4000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); Assert.Equal(0x2000u, peHeaders.PEHeader.SizeOfHeapCommit); Assert.Equal(0x8664, (ushort)peHeaders.CoffHeader.Machine); //AMD64 (K8) //default for non-arm, non-appcontainer outputs. EDMAURER: This is an intentional change from Dev11. //Should we find that it is too disruptive. We will consider rolling back. //It turns out to be too disruptive. Rolling back to 4.0 Assert.Equal(4, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(0, peHeaders.PEHeader.MinorSubsystemVersion); //The following ensure that the runtime startup stub was not emitted. It is not needed on modern operating systems. Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.Size); } [Fact] public void CheckCOFFAndPEOptionalHeadersARM() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithPlatform(Platform.Arm)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.False(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsDll); Assert.False(peHeaders.IsExe); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); // the default value is the same as the 32 bit default value Assert.Equal(0x10000000u, peHeaders.PEHeader.ImageBase); Assert.Equal(0x200, peHeaders.PEHeader.FileAlignment); Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE Assert.Equal(0x01c4, (ushort)peHeaders.CoffHeader.Machine); Assert.Equal(6, peHeaders.PEHeader.MajorSubsystemVersion); //Arm targets only run on 6.2 and above Assert.Equal(2, peHeaders.PEHeader.MinorSubsystemVersion); //The following ensure that the runtime startup stub was not emitted. It is not needed on modern operating systems. Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.Size); } [Fact] public void CheckCOFFAndPEOptionalHeadersAnyCPUExe() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.AnyCpu)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.False(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsExe); Assert.False(peHeaders.IsDll); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); Assert.Equal(0x00400000ul, peHeaders.PEHeader.ImageBase); Assert.Equal(0x00000200, peHeaders.PEHeader.FileAlignment); Assert.True(peHeaders.IsConsoleApplication); //should change if this is a windows app. Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfHeapCommit); //The following ensure that the runtime startup stub was emitted. It is not needed on modern operating systems. Assert.NotEqual(0, peHeaders.PEHeader.ImportAddressTableDirectory.RelativeVirtualAddress); Assert.NotEqual(0, peHeaders.PEHeader.ImportAddressTableDirectory.Size); Assert.NotEqual(0, peHeaders.PEHeader.ImportTableDirectory.RelativeVirtualAddress); Assert.NotEqual(0, peHeaders.PEHeader.ImportTableDirectory.Size); Assert.NotEqual(0, peHeaders.PEHeader.BaseRelocationTableDirectory.RelativeVirtualAddress); Assert.NotEqual(0, peHeaders.PEHeader.BaseRelocationTableDirectory.Size); } [Fact] public void CheckCOFFAndPEOptionalHeaders64Exe() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.True(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsExe); Assert.False(peHeaders.IsDll); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); Assert.Equal(0x0000000140000000ul, peHeaders.PEHeader.ImageBase); Assert.Equal(0x200, peHeaders.PEHeader.FileAlignment); //doesn't change based on architecture Assert.True(peHeaders.IsConsoleApplication); //should change if this is a windows app. Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE Assert.Equal(0x00400000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x4000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); //no sure why we don't bump this up relative to 32bit as well. Assert.Equal(0x2000u, peHeaders.PEHeader.SizeOfHeapCommit); } [Fact] public void CheckDllCharacteristicsHighEntropyVA() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(highEntropyVirtualAddressSpace: true))); //interesting COFF bits Assert.Equal(0x8560u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE | HIGH_ENTROPY_VA (0x20) } [WorkItem(764418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/764418")] [Fact] public void CheckDllCharacteristicsWinRtApp() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.CreateTestOptions(OutputKind.WindowsRuntimeApplication, OptimizationLevel.Debug)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.Equal(0x9540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE | IMAGE_DLLCHARACTERISTICS_APPCONTAINER (0x1000) } [Fact] public void CheckBaseAddress() { string source = @" class C { public static void Main() { } }"; // last four hex digits get zero'ed var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0x0000000010111111))); Assert.Equal(0x10110000ul, peHeaders.PEHeader.ImageBase); // test rounding up of values compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0x8000))); Assert.Equal(0x10000ul, peHeaders.PEHeader.ImageBase); // values less than 0x8000 get default baseaddress compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0x7fff))); Assert.Equal(0x00400000u, peHeaders.PEHeader.ImageBase); // default for 32bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream(options: EmitOptions.Default)); Assert.Equal(0x00400000u, peHeaders.PEHeader.ImageBase); // max for 32bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffff7fff))); Assert.Equal(0xffff0000ul, peHeaders.PEHeader.ImageBase); // max+1 for 32bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffff8000))); Assert.Equal(0x00400000u, peHeaders.PEHeader.ImageBase); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream(options: EmitOptions.Default)); Assert.Equal(0x0000000140000000u, peHeaders.PEHeader.ImageBase); // max for 64bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffffffffffff7fff))); Assert.Equal(0xffffffffffff0000ul, peHeaders.PEHeader.ImageBase); // max+1 for 64bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffffffffffff8000))); Assert.Equal(0x0000000140000000u, peHeaders.PEHeader.ImageBase); } [Fact] public void CheckFileAlignment() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(fileAlignment: 1024))); Assert.Equal(1024, peHeaders.PEHeader.FileAlignment); } #endregion [Fact] public void Bug10273() { string source = @" using System; public struct C1 { public int C; public static int B = 12; public void F(){} public int A; } public delegate void B(); public class A1 { public int C; public static int B = 12; public void F(){} public int A; public int I {get; set;} public void E(){} public int H {get; set;} public int G {get; set;} public event Action L; public void D(){} public event Action K; public event Action J; public partial class O { } public partial class N { } public partial class M { } public partial class N{} public partial class M{} public partial class O{} public void F(int x){} public void E(int x){} public void D(int x){} } namespace F{} public class G {} namespace E{} namespace D{} "; CompileAndVerify(source, sourceSymbolValidator: delegate (ModuleSymbol m) { string[] expectedGlobalMembers = { "C1", "B", "A1", "F", "G", "E", "D" }; var actualGlobalMembers = m.GlobalNamespace.GetMembers().Where(member => !member.IsImplicitlyDeclared).ToArray(); for (int i = 0; i < System.Math.Max(expectedGlobalMembers.Length, actualGlobalMembers.Length); i++) { Assert.Equal(expectedGlobalMembers[i], actualGlobalMembers[i].Name); } string[] expectedAMembers = { "C", "B", "F", "A", "<I>k__BackingField", "I", "get_I", "set_I", "E", "<H>k__BackingField", "H", "get_H", "set_H", "<G>k__BackingField", "G", "get_G", "set_G", "add_L", "remove_L", "L", "D", "add_K", "remove_K", "K", "add_J", "remove_J", "J", "O", "N", "M", "F", "E", "D", ".ctor", ".cctor" }; var actualAMembers = ((SourceModuleSymbol)m).GlobalNamespace.GetTypeMembers("A1").Single().GetMembers().ToArray(); for (int i = 0; i < System.Math.Max(expectedAMembers.Length, actualAMembers.Length); i++) { Assert.Equal(expectedAMembers[i], actualAMembers[i].Name); } string[] expectedBMembers = { ".ctor", "Invoke", "BeginInvoke", "EndInvoke" }; var actualBMembers = ((SourceModuleSymbol)m).GlobalNamespace.GetTypeMembers("B").Single().GetMembers().ToArray(); for (int i = 0; i < System.Math.Max(expectedBMembers.Length, actualBMembers.Length); i++) { Assert.Equal(expectedBMembers[i], actualBMembers[i].Name); } string[] expectedCMembers = {".cctor", "C", "B", "F", "A", ".ctor"}; var actualCMembers = ((SourceModuleSymbol)m).GlobalNamespace.GetTypeMembers("C1").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedCMembers, actualCMembers.Select(s => s.Name)); }, symbolValidator: delegate (ModuleSymbol m) { string[] expectedAMembers = {"C", "B", "A", "F", "get_I", "set_I", "E", "get_H", "set_H", "get_G", "set_G", "add_L", "remove_L", "D", "add_K", "remove_K", "add_J", "remove_J", "F", "E", "D", ".ctor", "I", "H", "G", "L", "K", "J", "O", "N", "M", }; var actualAMembers = m.GlobalNamespace.GetTypeMembers("A1").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedAMembers, actualAMembers.Select(s => s.Name)); string[] expectedBMembers = { ".ctor", "BeginInvoke", "EndInvoke", "Invoke" }; var actualBMembers = m.GlobalNamespace.GetTypeMembers("B").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedBMembers, actualBMembers.Select(s => s.Name)); string[] expectedCMembers = { "C", "B", "A", ".ctor", "F" }; var actualCMembers = m.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedCMembers, actualCMembers.Select(s => s.Name)); } ); } [WorkItem(543763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543763")] [Fact()] public void OptionalParamTypeAsDecimal() { string source = @" public class Test { public static decimal Goo(decimal d = 0) { return d; } public static void Main() { System.Console.WriteLine(Goo()); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(543932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543932")] [Fact] public void BranchCodeGenOnConditionDebug() { string source = @" public class Test { public static void Main() { int a_int = 0; if ((a_int != 0) || (false)) { System.Console.WriteLine(""CheckPoint-1""); } System.Console.WriteLine(""CheckPoint-2""); } }"; var compilation = CreateCompilation(source); CompileAndVerify(source, expectedOutput: "CheckPoint-2"); } [Fact] public void EmitAssemblyWithGivenName() { var name = "a"; var extension = ".dll"; var nameWithExtension = name + extension; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(nameWithExtension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameWithExtension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(name, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(nameWithExtension, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a.netmodule to b.netmodule [Fact] public void EmitModuleWithDifferentName() { var name = "a"; var extension = ".netmodule"; var outputName = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseModule.WithModuleName(name + extension), assemblyName: null); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal("?", assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: outputName + extension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.False(peReader.IsAssembly); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a.dll to b.dll - expected use case [Fact] public void EmitAssemblyWithDifferentName1() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride + extension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a.dll to b - odd, but allowable [Fact] public void EmitAssemblyWithDifferentName2() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a to b.dll - odd, but allowable [Fact] public void EmitAssemblyWithDifferentName3() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride + extension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a to b - odd, but allowable [Fact] public void EmitAssemblyWithDifferentName4() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } [WorkItem(570975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570975")] [Fact] public void Bug570975() { var source = @" public sealed class ContentType { public void M(System.Collections.Generic.Dictionary<object, object> p) { foreach (object parameterKey in p.Keys) { } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseModule, assemblyName: "ContentType"); compilation.VerifyDiagnostics(); using (ModuleMetadata block = ModuleMetadata.CreateFromStream(compilation.EmitToStream())) { var reader = block.MetadataReader; foreach (var typeRef in reader.TypeReferences) { EntityHandle scope = reader.GetTypeReference(typeRef).ResolutionScope; if (scope.Kind == HandleKind.TypeReference) { Assert.InRange(reader.GetRowNumber(scope), 1, reader.GetRowNumber(typeRef) - 1); } } } } [Fact] public void IllegalNameOverride() { var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var result = compilation.Emit(new MemoryStream(), options: new EmitOptions(outputNameOverride: "x\0x")); result.Diagnostics.Verify( // error CS2041: Invalid output name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_InvalidOutputName).WithArguments("Name contains invalid characters.").WithLocation(1, 1)); Assert.False(result.Success); } // Verify via MetadataReader - comp option [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes3() { string source = @" class C { public static void Main() { } }"; // Setting the CompilationOption.AllowUnsafe causes an entry to be inserted into the DeclSecurity table var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - comp option, module case [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes4() { string source = @" class C { public static void Main() { } }"; // Setting the CompilationOption.AllowUnsafe causes an entry to be inserted into the DeclSecurity table var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule)); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, verify: Verification.Skipped, symbolValidator: module => { //no assembly => no decl security row ValidateDeclSecurity(module); }); } // Verify via MetadataReader - attr in source [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes5() { // Writing the attributes in the source should have the same effect as the compilation option. string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - two attrs in source, same action [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes6() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have the SecurityAction, so they should be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (6,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001" + // argument value (true) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - two attrs in source, different actions [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes7() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have different SecurityActions, so they should not be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (6,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - one attr in source, one synthesized, same action [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes8() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have the SecurityAction, so they should be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001" + // argument value (true) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - one attr in source, one synthesized, different actions [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes9() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have different SecurityActions, so they should not be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } [Fact] [WorkItem(545651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545651")] private void TestReferenceToNestedGenericType() { string p1 = @"public class Goo<T> { }"; string p2 = @"using System; public class Test { public class C<T> {} public class J<T> : C<Goo<T>> { } public static void Main() { Console.WriteLine(typeof(J<int>).BaseType.Equals(typeof(C<Goo<int>>)) ? 0 : 1); } }"; var c1 = CreateCompilation(p1, options: TestOptions.ReleaseDll, assemblyName: Guid.NewGuid().ToString()); CompileAndVerify(p2, new[] { MetadataReference.CreateFromStream(c1.EmitToStream()) }, expectedOutput: "0"); } [WorkItem(546450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546450")] [Fact] public void EmitNetModuleWithReferencedNetModule() { string source1 = @"public class A {}"; string source2 = @"public class B: A {}"; var comp = CreateCompilation(source1, options: TestOptions.ReleaseModule); var metadataRef = ModuleMetadata.CreateFromStream(comp.EmitToStream()).GetReference(); CompileAndVerify(source2, references: new[] { metadataRef }, options: TestOptions.ReleaseModule, verify: Verification.Fails); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(530879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530879")] public void TestCompilationEmitUsesDifferentStreamsForBinaryAndPdb() { string p1 = @"public class C1 { }"; var c1 = CreateCompilation(p1); var tmpDir = Temp.CreateDirectory(); var dllPath = Path.Combine(tmpDir.Path, "assemblyname.dll"); var pdbPath = Path.Combine(tmpDir.Path, "assemblyname.pdb"); var result = c1.Emit(dllPath, pdbPath); Assert.True(result.Success, "Compilation failed"); Assert.Empty(result.Diagnostics); Assert.True(File.Exists(dllPath), "DLL does not exist"); Assert.True(File.Exists(pdbPath), "PDB does not exist"); } [Fact, WorkItem(540777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777"), WorkItem(546354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546354")] public void CS0219WRN_UnreferencedVarAssg_ConditionalOperator() { var text = @" class Program { static void Main(string[] args) { bool b; int s = (b = false) ? 5 : 100; // Warning } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (7,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // int s = (b = false) ? 5 : 100; // Warning Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (6,14): warning CS0219: The variable 'b' is assigned but its value is never used // bool b; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b").WithArguments("b")); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_01() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); // Confirm that suppressing the old alink warning 1607 shuts off WRN_ConflictingMachineAssembly var warnings = new System.Collections.Generic.Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); useCompilation = useCompilation.WithOptions(useCompilation.Options.WithSpecificDiagnosticOptions(warnings)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_02() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions, // error CS8010: Agnostic assembly cannot have a processor specific module 'PlatformMismatch.netmodule'. Diagnostic(ErrorCode.ERR_AgnosticToMachineModule).WithArguments("PlatformMismatch.netmodule")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // error CS8011: Assembly and module 'PlatformMismatch.netmodule' cannot target different processors. Diagnostic(ErrorCode.ERR_ConflictingMachineModule).WithArguments("PlatformMismatch.netmodule")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu)); // no CS8010 when building a module and adding a module that has a conflict. useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_03() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_04() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.X86), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // error CS8011: Assembly and module 'PlatformMismatch.netmodule' cannot target different processors. Diagnostic(ErrorCode.ERR_ConflictingMachineModule).WithArguments("PlatformMismatch.netmodule")); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_05() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_06() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_07() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_08() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [Fact, WorkItem(769741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769741")] public void Bug769741() { var comp = CreateEmptyCompilation("", new[] { TestReferences.SymbolsTests.netModule.x64COFF }, options: TestOptions.DebugDll); // modules not supported in ref emit CompileAndVerify(comp, verify: Verification.Fails); Assert.NotSame(comp.Assembly.CorLibrary, comp.Assembly); comp.GetSpecialType(SpecialType.System_Int32); } [Fact] public void FoldMethods() { string source = @" class Viewable { static void Main() { var v = new Viewable(); var x = v.P1; var y = x && v.P2; } bool P1 { get { return true; } } bool P2 { get { return true; } } } "; var compilation = CreateCompilation(source, null, TestOptions.ReleaseDll); var peReader = ModuleMetadata.CreateFromStream(compilation.EmitToStream()).Module.GetMetadataReader(); int P1RVA = 0; int P2RVA = 0; foreach (var handle in peReader.TypeDefinitions) { var typeDef = peReader.GetTypeDefinition(handle); if (peReader.StringComparer.Equals(typeDef.Name, "Viewable")) { foreach (var m in typeDef.GetMethods()) { var method = peReader.GetMethodDefinition(m); if (peReader.StringComparer.Equals(method.Name, "get_P1")) { P1RVA = method.RelativeVirtualAddress; } if (peReader.StringComparer.Equals(method.Name, "get_P2")) { P2RVA = method.RelativeVirtualAddress; } } } } Assert.NotEqual(0, P1RVA); Assert.Equal(P2RVA, P1RVA); } private static bool SequenceMatches(byte[] buffer, int startIndex, byte[] pattern) { for (int i = 0; i < pattern.Length; i++) { if (buffer[startIndex + i] != pattern[i]) { return false; } } return true; } private static int IndexOfPattern(byte[] buffer, int startIndex, byte[] pattern) { // Naive linear search for target within buffer int end = buffer.Length - pattern.Length; for (int i = startIndex; i < end; i++) { if (SequenceMatches(buffer, i, pattern)) { return i; } } return -1; } [Fact, WorkItem(1669, "https://github.com/dotnet/roslyn/issues/1669")] public void FoldMethods2() { // Verifies that IL folding eliminates duplicate copies of small method bodies by // examining the emitted binary. string source = @" class C { ulong M() => 0x8675309ABCDE4225UL; long P => -8758040459200282075L; } "; var compilation = CreateCompilation(source, null, TestOptions.ReleaseDll); using (var stream = compilation.EmitToStream()) { var bytes = new byte[stream.Length]; Assert.Equal(bytes.Length, stream.Read(bytes, 0, bytes.Length)); // The constant should appear exactly once byte[] pattern = new byte[] { 0x25, 0x42, 0xDE, 0xBC, 0x9A, 0x30, 0x75, 0x86 }; int firstMatch = IndexOfPattern(bytes, 0, pattern); Assert.True(firstMatch >= 0, "Couldn't find the expected byte pattern in the output."); int secondMatch = IndexOfPattern(bytes, firstMatch + 1, pattern); Assert.True(secondMatch < 0, "Expected to find just one occurrence of the pattern in the output."); } } [Fact] public void BrokenOutStream() { //These tests ensure that users supplying a broken stream implementation via the emit API //get exceptions enabling them to attribute the failure to their code and to debug. string source = @"class Goo {}"; var compilation = CreateCompilation(source); var output = new BrokenStream(); output.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation.Emit(output); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the Portable Executable file. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(output.ThrownException.ToString()).WithLocation(1, 1)); // Stream.Position is not called: output.BreakHow = BrokenStream.BreakHowType.ThrowOnSetPosition; result = compilation.Emit(output); result.Diagnostics.Verify(); // disposed stream is not writable var outReal = new MemoryStream(); outReal.Dispose(); Assert.Throws<ArgumentException>(() => compilation.Emit(outReal)); } [Fact] public void BrokenPortablePdbStream() { string source = @"class Goo {}"; var compilation = CreateCompilation(source); using (new EnsureEnglishUICulture()) using (var output = new MemoryStream()) { var pdbStream = new BrokenStream(); pdbStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation.Emit(output, pdbStream, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/23760")] public void BrokenPDBStream() { string source = @"class Goo {}"; var compilation = CreateCompilation(source, null, TestOptions.DebugDll); var output = new MemoryStream(); var pdb = new BrokenStream(); pdb.BreakHow = BrokenStream.BreakHowType.ThrowOnSetLength; var result = compilation.Emit(output, pdbStream: pdb); // error CS0041: Unexpected error writing debug information -- 'Exception from HRESULT: 0x806D0004' var err = result.Diagnostics.Single(); Assert.Equal((int)ErrorCode.FTL_DebugEmitFailure, err.Code); Assert.Equal(1, err.Arguments.Count); var ioExceptionMessage = new IOException().Message; Assert.Equal(ioExceptionMessage, (string)err.Arguments[0]); pdb.Dispose(); result = compilation.Emit(output, pdbStream: pdb); // error CS0041: Unexpected error writing debug information -- 'Exception from HRESULT: 0x806D0004' err = result.Diagnostics.Single(); Assert.Equal((int)ErrorCode.FTL_DebugEmitFailure, err.Code); Assert.Equal(1, err.Arguments.Count); Assert.Equal(ioExceptionMessage, (string)err.Arguments[0]); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodulesWithPrivateImplementationDetails() { var s1 = @" public class A { private static char[] contents = { 'H', 'e', 'l', 'l', 'o', ',', ' ' }; public static string M1() { return new string(contents); } }"; var s2 = @" public class B : A { private static char[] contents = { 'w', 'o', 'r', 'l', 'd', '!' }; public static string M2() { return new string(contents); } }"; var s3 = @" public class Program { public static void Main(string[] args) { System.Console.Write(A.M1()); System.Console.WriteLine(B.M2()); } }"; var comp1 = CreateCompilation(s1, options: TestOptions.ReleaseModule); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilation(s2, options: TestOptions.ReleaseModule, references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); var comp3 = CreateCompilation(s3, options: TestOptions.ReleaseExe, references: new[] { ref1, ref2 }); // Before the bug was fixed, the PrivateImplementationDetails classes clashed, resulting in the commented-out error below. comp3.VerifyDiagnostics( ////// error CS0101: The namespace '<global namespace>' already contains a definition for '<PrivateImplementationDetails>' ////Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("<PrivateImplementationDetails>", "<global namespace>").WithLocation(1, 1) ); CompileAndVerify(comp3, expectedOutput: "Hello, world!"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodulesWithAnonymousTypes() { var s1 = @" public class A { internal object o1 = new { hello = 1, world = 2 }; public static string M1() { return ""Hello, ""; } }"; var s2 = @" public class B : A { internal object o2 = new { hello = 1, world = 2 }; public static string M2() { return ""world!""; } }"; var s3 = @" public class Program { public static void Main(string[] args) { System.Console.Write(A.M1()); System.Console.WriteLine(B.M2()); } }"; var comp1 = CreateCompilation(s1, options: TestOptions.ReleaseModule.WithModuleName("A")); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilation(s2, options: TestOptions.ReleaseModule.WithModuleName("B"), references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); var comp3 = CreateCompilation(s3, options: TestOptions.ReleaseExe.WithModuleName("C"), references: new[] { ref1, ref2 }); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, expectedOutput: "Hello, world!"); } /// <summary> /// Ordering of anonymous type definitions /// in metadata should be deterministic. /// </summary> [Fact] public void AnonymousTypeMetadataOrder() { var source = @"class C1 { object F = new { A = 1, B = 2 }; } class C2 { object F = new { a = 3, b = 4 }; } class C3 { object F = new { AB = 3 }; } class C4 { object F = new { a = 1, B = 2 }; } class C5 { object F = new { a = 1, B = 2 }; } class C6 { object F = new { Ab = 5 }; }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var bytes = compilation.EmitToArray(); using (var metadata = ModuleMetadata.CreateFromImage(bytes)) { var reader = metadata.MetadataReader; var actualNames = reader.GetTypeDefNames().Select(h => reader.GetString(h)); var expectedNames = new[] { "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2`1", "<>f__AnonymousType3`2", "<>f__AnonymousType4`1", "C1", "C2", "C3", "C4", "C5", "C6", }; AssertEx.Equal(expectedNames, actualNames); } } /// <summary> /// Ordering of synthesized delegates in /// metadata should be deterministic. /// </summary> [WorkItem(1440, "https://github.com/dotnet/roslyn/issues/1440")] [Fact] public void SynthesizedDelegateMetadataOrder() { var source = @"class C1 { static void M(dynamic d, object x, int y) { d(1, ref x, out y); } } class C2 { static object M(dynamic d, object o) { return d(o, ref o); } } class C3 { static void M(dynamic d, object o) { d(ref o); } } class C4 { static int M(dynamic d, object o) { return d(ref o, 2); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new[] { CSharpRef }); var bytes = compilation.EmitToArray(); using (var metadata = ModuleMetadata.CreateFromImage(bytes)) { var reader = metadata.MetadataReader; var actualNames = reader.GetTypeDefNames().Select(h => reader.GetString(h)); var expectedNames = new[] { "<Module>", "<>A{00000010}`3", "<>A{00000140}`5", "<>F{00000010}`5", "<>F{00000040}`5", "C1", "C2", "C3", "C4", "<>o__0", "<>o__0", "<>o__0", "<>o__0", }; AssertEx.Equal(expectedNames, actualNames); } } [Fact] [WorkItem(3240, "https://github.com/dotnet/roslyn/pull/8227")] public void FailingEmitter() { string source = @" public class X { public static void Main() { } }"; var compilation = CreateCompilation(source); var broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation.Emit(broken); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the Portable Executable file. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(broken.ThrownException.ToString()).WithLocation(1, 1)); } [Fact] public void BadPdbStreamWithPortablePdbEmit() { var comp = CreateCompilation("class C {}"); var broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; using (new EnsureEnglishUICulture()) using (var peStream = new MemoryStream()) { var portablePdbOptions = EmitOptions.Default .WithDebugInformationFormat(DebugInformationFormat.PortablePdb); var result = comp.Emit(peStream, pdbStream: broken, options: portablePdbOptions); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)); // Allow for cancellation broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.CancelOnWrite; Assert.Throws<OperationCanceledException>(() => comp.Emit(peStream, pdbStream: broken, options: portablePdbOptions)); } } [Fact] [WorkItem(9308, "https://github.com/dotnet/roslyn/issues/9308")] public void FailingEmitterAllowsCancellationExceptionsThrough() { string source = @" public class X { public static void Main() { } }"; var compilation = CreateCompilation(source); var broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.CancelOnWrite; Assert.Throws<OperationCanceledException>(() => compilation.Emit(broken)); } [Fact] [WorkItem(11691, "https://github.com/dotnet/roslyn/issues/11691")] public void ObsoleteAttributeOverride() { string source = @" using System; public abstract class BaseClass<T> { public abstract int Method(T input); } public class DerivingClass<T> : BaseClass<T> { [Obsolete(""Deprecated"")] public override void Method(T input) { throw new NotImplementedException(); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,26): warning CS0809: Obsolete member 'DerivingClass<T>.Method(T)' overrides non-obsolete member 'BaseClass<T>.Method(T)' // public override void Method(T input) Diagnostic(ErrorCode.WRN_ObsoleteOverridingNonObsolete, "Method").WithArguments("DerivingClass<T>.Method(T)", "BaseClass<T>.Method(T)").WithLocation(11, 26), // (11,26): error CS0508: 'DerivingClass<T>.Method(T)': return type must be 'int' to match overridden member 'BaseClass<T>.Method(T)' // public override void Method(T input) Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "Method").WithArguments("DerivingClass<T>.Method(T)", "BaseClass<T>.Method(T)", "int").WithLocation(11, 26)); } [Fact] public void CompileAndVerifyModuleIncludesAllModules() { // Before this change, CompileAndVerify() didn't include other modules when testing a PEModule. // Verify that symbols from other modules are accessible as well. var modRef = CreateCompilation("public class A { }", options: TestOptions.ReleaseModule, assemblyName: "refMod").EmitToImageReference(); var comp = CreateCompilation("public class B : A { }", references: new[] { modRef }, assemblyName: "sourceMod"); CompileAndVerify(comp, symbolValidator: module => { var b = module.GlobalNamespace.GetTypeMember("B"); Assert.Equal("B", b.Name); Assert.False(b.IsErrorType()); Assert.Equal("sourceMod.dll", b.ContainingModule.Name); var a = b.BaseType(); Assert.Equal("A", a.Name); Assert.False(a.IsErrorType()); Assert.Equal("refMod.netmodule", a.ContainingModule.Name); }); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorDoesNotEmit_GeneralDiagnosticOption() { var options = TestOptions.DebugDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); TestWarnAsErrorDoesNotEmitCore(options); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorDoesNotEmit_SpecificDiagnosticOption() { var options = TestOptions.DebugDll.WithSpecificDiagnosticOptions("CS0169", ReportDiagnostic.Error); TestWarnAsErrorDoesNotEmitCore(options); } private void TestWarnAsErrorDoesNotEmitCore(CSharpCompilationOptions options) { string source = @" class X { int _f; }"; var compilation = CreateCompilation(source, options: options); using var output = new MemoryStream(); using var pdbStream = new MemoryStream(); using var xmlDocumentationStream = new MemoryStream(); using var win32ResourcesStream = compilation.CreateDefaultWin32Resources(versionResource: true, noManifest: false, manifestContents: null, iconInIcoFormat: null); var emitResult = compilation.Emit(output, pdbStream, xmlDocumentationStream, win32ResourcesStream); Assert.False(emitResult.Success); Assert.Equal(0, output.Length); Assert.Equal(0, pdbStream.Length); // https://github.com/dotnet/roslyn/issues/37996 tracks revisiting the below behavior. Assert.True(xmlDocumentationStream.Length > 0); emitResult.Diagnostics.Verify( // (4,9): error CS0169: The field 'X._f' is never used // int _f; Diagnostic(ErrorCode.WRN_UnreferencedField, "_f").WithArguments("X._f").WithLocation(4, 9).WithWarningAsError(true)); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorWithMetadataOnlyImageDoesEmit_GeneralDiagnosticOption() { var options = TestOptions.DebugDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); TestWarnAsErrorWithMetadataOnlyImageDoesEmitCore(options); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorWithMetadataOnlyImageDoesEmit_SpecificDiagnosticOptions() { var options = TestOptions.DebugDll.WithSpecificDiagnosticOptions("CS0612", ReportDiagnostic.Error); TestWarnAsErrorWithMetadataOnlyImageDoesEmitCore(options); } private void TestWarnAsErrorWithMetadataOnlyImageDoesEmitCore(CSharpCompilationOptions options) { string source = @" public class X { public void M(Y y) { } } [System.Obsolete] public class Y { } "; var compilation = CreateCompilation(source, options: options); using var output = new MemoryStream(); var emitOptions = new EmitOptions(metadataOnly: true); var emitResult = compilation.Emit(output, options: emitOptions); Assert.True(emitResult.Success); Assert.True(output.Length > 0); emitResult.Diagnostics.Verify( // (4,19): error CS0612: 'Y' is obsolete // public void M(Y y) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Y").WithArguments("Y").WithLocation(4, 19).WithWarningAsError(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.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Roslyn.Test.Utilities.TestMetadata; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Emit { public partial class CompilationEmitTests : EmitMetadataTestBase { [Fact] public void CompilationEmitDiagnostics() { // Check that Compilation.Emit actually produces compilation errors. string source = @" class X { public void Main() { const int x = 5; x = x; // error; assigning to const. } }"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } emitResult.Diagnostics.Verify( // (7,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "x")); } [Fact] public void CompilationEmitWithQuotedMainType() { // Check that compilation with quoted main switch argument produce diagnostic. // MSBuild can return quoted main argument value which is removed from the command line arguments or by parsing // command line arguments, but we DO NOT unquote arguments which are provided by // the WithMainTypeName function - (was originally exposed through using // a Cyrillic Namespace And building Using MSBuild.) string source = @" namespace abc { public class X { public static void Main() { } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("abc.X")); compilation.VerifyDiagnostics(); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("\"abc.X\"")); compilation.VerifyDiagnostics(// error CS1555: Could not find '"abc.X"' specified for Main method Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("\"abc.X\"")); // Verify use of Cyrillic namespace results in same behavior source = @" namespace решения { public class X { public static void Main() { } } }"; compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("решения.X")); compilation.VerifyDiagnostics(); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithMainTypeName("\"решения.X\"")); compilation.VerifyDiagnostics(Diagnostic(ErrorCode.ERR_MainClassNotFound).WithArguments("\"решения.X\"")); } [Fact] public void CompilationGetDiagnostics() { // Check that Compilation.GetDiagnostics and Compilation.GetDeclarationDiagnostics work as expected. string source = @" class X { private Blah q; public void Main() { const int x = 5; x = x; // error; assigning to const. } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (4,13): error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) // private Blah q; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Blah").WithArguments("Blah"), // (8,9): error CS0131: The left-hand side of an assignment must be a variable, property or indexer // x = x; // error; assigning to const. Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "x"), // (4,18): warning CS0169: The field 'X.q' is never used // private Blah q; Diagnostic(ErrorCode.WRN_UnreferencedField, "q").WithArguments("X.q")); } // Check that Emit produces syntax, declaration, and method body errors. [Fact] public void EmitDiagnostics() { CSharpCompilation comp = CreateCompilation(@" namespace N { class X { public Blah field; private static readonly int ro; public static void Main() { ro = 4; } } } namespace N.; "); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = comp.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.False(emitResult.Success); emitResult.Diagnostics.Verify( // (13,13): error CS1001: Identifier expected // namespace N.; Diagnostic(ErrorCode.ERR_IdentifierExpected, ";").WithLocation(13, 13), // (13,11): error CS8942: File-scoped namespace must precede all other members in a file. // namespace N.; Diagnostic(ErrorCode.ERR_FileScopedNamespaceNotBeforeAllMembers, "N.").WithLocation(13, 11), // (4,16): error CS0246: The type or namespace name 'Blah' could not be found (are you missing a using directive or an assembly reference?) // public Blah field; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Blah").WithArguments("Blah").WithLocation(4, 16), // (8,13): error CS0198: A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) // ro = 4; Diagnostic(ErrorCode.ERR_AssgReadonlyStatic, "ro").WithLocation(8, 13), // (4,21): warning CS0649: Field 'X.field' is never assigned to, and will always have its default value null // public Blah field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("N.X.field", "null").WithLocation(4, 21)); } // Check that EmitMetadataOnly works [Fact] public void EmitMetadataOnly() { CSharpCompilation comp = CreateCompilation(@" namespace Goo.Bar { public class Test1 { public static void SayHello() { Console.WriteLine(""hello""); } public int x; private int y; public Test1() { x = 17; } public string goo(int a) { return a.ToString(); } } } "); EmitResult emitResult; byte[] mdOnlyImage; using (var output = new MemoryStream()) { emitResult = comp.Emit(output, options: new EmitOptions(metadataOnly: true)); mdOnlyImage = output.ToArray(); } Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); Assert.True(mdOnlyImage.Length > 0, "no metadata emitted"); var srcUsing = @" using System; using Goo.Bar; class Test2 { public static void Main() { Test1.SayHello(); Console.WriteLine(new Test1().x); } } "; CSharpCompilation compUsing = CreateCompilation(srcUsing, new[] { MetadataReference.CreateFromImage(mdOnlyImage.AsImmutableOrNull()) }); using (var output = new MemoryStream()) { emitResult = compUsing.Emit(output); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); Assert.True(output.ToArray().Length > 0, "no metadata emitted"); } } [Fact] public void EmitRefAssembly_PrivateMain() { CSharpCompilation comp = CreateCompilation(@" public class C { internal static void Main() { System.Console.WriteLine(""hello""); } } ", options: TestOptions.DebugExe); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { // Previously, this would crash when trying to get the entry point for the ref assembly // (but the Main method is not emitted in the ref assembly...) EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyEntryPoint(output, expectZero: false); VerifyMethods(output, "C", new[] { "void C.Main()", "C..ctor()" }); VerifyMvid(output, hasMvidSection: false); VerifyEntryPoint(metadataOutput, expectZero: true); VerifyMethods(metadataOutput, "C", new[] { "C..ctor()" }); VerifyMvid(metadataOutput, hasMvidSection: true); } void VerifyEntryPoint(MemoryStream stream, bool expectZero) { stream.Position = 0; int entryPoint = new PEHeaders(stream).CorHeader.EntryPointTokenOrRelativeVirtualAddress; Assert.Equal(expectZero, entryPoint == 0); } } private class TestResourceSectionBuilder : ResourceSectionBuilder { public TestResourceSectionBuilder() { } protected override void Serialize(BlobBuilder builder, SectionLocation location) { builder.WriteInt32(0x12345678); builder.WriteInt32(location.PointerToRawData); builder.WriteInt32(location.RelativeVirtualAddress); } } private class TestPEBuilder : ManagedPEBuilder { public static readonly Guid s_mvid = Guid.Parse("a78fa2c3-854e-42bf-8b8d-75a450a6dc18"); public TestPEBuilder(PEHeaderBuilder header, MetadataRootBuilder metadataRootBuilder, BlobBuilder ilStream, ResourceSectionBuilder nativeResources) : base(header, metadataRootBuilder, ilStream, nativeResources: nativeResources) { } protected override ImmutableArray<Section> CreateSections() { return base.CreateSections().Add( new Section(".mvid", SectionCharacteristics.MemRead | SectionCharacteristics.ContainsInitializedData | SectionCharacteristics.MemDiscardable)); } protected override BlobBuilder SerializeSection(string name, SectionLocation location) { if (name.Equals(".mvid", StringComparison.Ordinal)) { var sectionBuilder = new BlobBuilder(); sectionBuilder.WriteGuid(s_mvid); return sectionBuilder; } return base.SerializeSection(name, location); } } [Fact] public void MvidSectionNotFirst() { var ilBuilder = new BlobBuilder(); var metadataBuilder = new MetadataBuilder(); var peBuilder = new TestPEBuilder( PEHeaderBuilder.CreateLibraryHeader(), new MetadataRootBuilder(metadataBuilder), ilBuilder, nativeResources: new TestResourceSectionBuilder()); var peBlob = new BlobBuilder(); peBuilder.Serialize(peBlob); var peStream = new MemoryStream(); peBlob.WriteContentTo(peStream); peStream.Position = 0; using (var peReader = new PEReader(peStream)) { AssertEx.Equal(new[] { ".text", ".rsrc", ".reloc", ".mvid" }, peReader.PEHeaders.SectionHeaders.Select(h => h.Name)); peStream.Position = 0; var mvid = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(peStream); Assert.Equal(TestPEBuilder.s_mvid, mvid); } } /// <summary> /// Extract the MVID using two different methods (PEReader and MvidReader) and compare them. /// We only expect an .mvid section in ref assemblies. /// </summary> private void VerifyMvid(MemoryStream stream, bool hasMvidSection) { stream.Position = 0; using (var reader = new PEReader(stream)) { var metadataReader = reader.GetMetadataReader(); Guid mvidFromModuleDefinition = metadataReader.GetGuid(metadataReader.GetModuleDefinition().Mvid); stream.Position = 0; var mvidFromMvidReader = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(stream); Assert.NotEqual(Guid.Empty, mvidFromModuleDefinition); if (hasMvidSection) { Assert.Equal(mvidFromModuleDefinition, mvidFromMvidReader); } else { Assert.Equal(Guid.Empty, mvidFromMvidReader); } } } [Fact] public void EmitRefAssembly_PrivatePropertySetter() { CSharpCompilation comp = CreateCompilation(@" public class C { public int PrivateSetter { get; private set; } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyMethods(output, "C", new[] { "System.Int32 C.<PrivateSetter>k__BackingField", "System.Int32 C.PrivateSetter.get", "void C.PrivateSetter.set", "C..ctor()", "System.Int32 C.PrivateSetter { get; private set; }" }); VerifyMethods(metadataOutput, "C", new[] { "System.Int32 C.PrivateSetter.get", "C..ctor()", "System.Int32 C.PrivateSetter { get; }" }); VerifyMvid(output, hasMvidSection: false); VerifyMvid(metadataOutput, hasMvidSection: true); } } [Fact] public void EmitRefAssembly_PrivatePropertyGetter() { CSharpCompilation comp = CreateCompilation(@" public class C { public int PrivateGetter { private get; set; } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyMethods(output, "C", new[] { "System.Int32 C.<PrivateGetter>k__BackingField", "System.Int32 C.PrivateGetter.get", "void C.PrivateGetter.set", "C..ctor()", "System.Int32 C.PrivateGetter { private get; set; }" }); VerifyMethods(metadataOutput, "C", new[] { "void C.PrivateGetter.set", "C..ctor()", "System.Int32 C.PrivateGetter { set; }" }); } } [Fact] public void EmitRefAssembly_PrivateIndexerGetter() { CSharpCompilation comp = CreateCompilation(@" public class C { public int this[int i] { private get { return 0; } set { } } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); VerifyMethods(output, "C", new[] { "System.Int32 C.this[System.Int32 i].get", "void C.this[System.Int32 i].set", "C..ctor()", "System.Int32 C.this[System.Int32 i] { private get; set; }" }); VerifyMethods(metadataOutput, "C", new[] { "void C.this[System.Int32 i].set", "C..ctor()", "System.Int32 C.this[System.Int32 i] { set; }" }); } } [Fact] public void EmitRefAssembly_SealedPropertyWithInternalInheritedGetter() { CSharpCompilation comp = CreateCompilation(@" public class Base { public virtual int Property { internal get { return 0; } set { } } } public class C : Base { public sealed override int Property { set { } } } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); emitResult.Diagnostics.Verify(); Assert.True(emitResult.Success); VerifyMethods(output, "C", new[] { "void C.Property.set", "C..ctor()", "System.Int32 C.Property.get", "System.Int32 C.Property { internal get; set; }" }); // A getter is synthesized on C.Property so that it can be marked as sealed. It is emitted despite being internal because it is virtual. VerifyMethods(metadataOutput, "C", new[] { "void C.Property.set", "C..ctor()", "System.Int32 C.Property.get", "System.Int32 C.Property { internal get; set; }" }); } } [Fact] public void EmitRefAssembly_PrivateAccessorOnEvent() { CSharpCompilation comp = CreateCompilation(@" public class C { public event System.Action PrivateAdder { private add { } remove { } } public event System.Action PrivateRemover { add { } private remove { } } } "); comp.VerifyDiagnostics( // (4,47): error CS1609: Modifiers cannot be placed on event accessor declarations // public event System.Action PrivateAdder { private add { } remove { } } Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "private").WithLocation(4, 47), // (5,57): error CS1609: Modifiers cannot be placed on event accessor declarations // public event System.Action PrivateRemover { add { } private remove { } } Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "private").WithLocation(5, 57) ); } [Fact] [WorkItem(38444, "https://github.com/dotnet/roslyn/issues/38444")] public void EmitRefAssembly_InternalAttributeConstructor() { CSharpCompilation comp = CreateCompilation(@" using System; internal class SomeAttribute : Attribute { internal SomeAttribute() { } } [Some] public class C { } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); emitResult.Diagnostics.Verify(); Assert.True(emitResult.Success); VerifyMethods(output, "C", new[] { "C..ctor()" }); VerifyMethods(metadataOutput, "C", new[] { "C..ctor()" }); VerifyMethods(output, "SomeAttribute", new[] { "SomeAttribute..ctor()" }); VerifyMethods(metadataOutput, "SomeAttribute", new[] { "SomeAttribute..ctor()" }); } } [Fact] [WorkItem(38444, "https://github.com/dotnet/roslyn/issues/38444")] public void EmitRefAssembly_InternalAttributeConstructor_DoesntIncludeMethodsOrStaticConstructors() { CSharpCompilation comp = CreateCompilation(@" using System; internal class SomeAttribute : Attribute { internal SomeAttribute() { } static SomeAttribute() { } internal void F() { } } [Some] public class C { } "); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { EmitResult emitResult = comp.Emit(output, metadataPEStream: metadataOutput, options: new EmitOptions(includePrivateMembers: false)); emitResult.Diagnostics.Verify(); Assert.True(emitResult.Success); VerifyMethods(output, "C", new[] { "C..ctor()" }); VerifyMethods(metadataOutput, "C", new[] { "C..ctor()" }); VerifyMethods(output, "SomeAttribute", new[] { "SomeAttribute..ctor()", "SomeAttribute..cctor()", "void SomeAttribute.F()" }); VerifyMethods(metadataOutput, "SomeAttribute", new[] { "SomeAttribute..ctor()" }); } } private static void VerifyMethods(MemoryStream stream, string containingType, string[] expectedMethods) { stream.Position = 0; var metadataRef = AssemblyMetadata.CreateFromImage(stream.ToArray()).GetReference(); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataRef }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( expectedMethods, compWithMetadata.GetMember<NamedTypeSymbol>(containingType).GetMembers().Select(m => m.ToTestDisplayString())); } [Fact] public void RefAssembly_HasReferenceAssemblyAttribute() { var emitRefAssembly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var attributes = reader.GetAssemblyDefinition().GetCustomAttributes(); AssertEx.Equal(new[] { "MemberReference:Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor(Int32)", "MemberReference:Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor()", "MemberReference:Void System.Diagnostics.DebuggableAttribute..ctor(DebuggingModes)", "MemberReference:Void System.Runtime.CompilerServices.ReferenceAssemblyAttribute..ctor()" }, attributes.Select(a => MetadataReaderUtils.Dump(reader, reader.GetCustomAttribute(a).Constructor))); }; CompileAndVerify("", emitOptions: emitRefAssembly, assemblyValidator: assemblyValidator); } [Fact] public void RefAssembly_HandlesMissingReferenceAssemblyAttribute() { var emitRefAssembly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var attributes = reader.GetAssemblyDefinition().GetCustomAttributes(); AssertEx.SetEqual(attributes.Select(a => MetadataReaderUtils.Dump(reader, reader.GetCustomAttribute(a).Constructor)), new string[] { "MemberReference:Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor(Int32)", "MemberReference:Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor()", "MemberReference:Void System.Diagnostics.DebuggableAttribute..ctor(DebuggingModes)" }); }; var comp = CreateCompilation(""); comp.MakeMemberMissing(WellKnownMember.System_Runtime_CompilerServices_ReferenceAssemblyAttribute__ctor); CompileAndVerifyCommon(compilation: comp, emitOptions: emitRefAssembly, assemblyValidator: assemblyValidator); } [Fact] public void RefAssembly_ReferenceAssemblyAttributeAlsoInSource() { var emitRefAssembly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); Action<PEAssembly> assemblyValidator = assembly => { var reader = assembly.GetMetadataReader(); var attributes = reader.GetAssemblyDefinition().GetCustomAttributes(); AssertEx.Equal(new string[] { "MemberReference:Void System.Runtime.CompilerServices.CompilationRelaxationsAttribute..ctor(Int32)", "MemberReference:Void System.Runtime.CompilerServices.RuntimeCompatibilityAttribute..ctor()", "MemberReference:Void System.Diagnostics.DebuggableAttribute..ctor(DebuggingModes)", "MemberReference:Void System.Runtime.CompilerServices.ReferenceAssemblyAttribute..ctor()" }, attributes.Select(a => MetadataReaderUtils.Dump(reader, reader.GetCustomAttribute(a).Constructor))); }; string source = @"[assembly:System.Runtime.CompilerServices.ReferenceAssembly()]"; CompileAndVerify(source, emitOptions: emitRefAssembly, assemblyValidator: assemblyValidator); } [Theory] [InlineData("public int M() { return 1; }", "public int M() { return 2; }", Match.BothMetadataAndRefOut)] [InlineData("public int M() { return 1; }", "public int M() { error(); }", Match.BothMetadataAndRefOut)] [InlineData("private void M() { }", "", Match.RefOut)] [InlineData("internal void M() { }", "", Match.RefOut)] [InlineData("private protected void M() { }", "", Match.RefOut)] [InlineData("private void M() { dynamic x = 1; }", "", Match.RefOut)] // no reference added from method bodies [InlineData(@"private void M() { var x = new { id = 1 }; }", "", Match.RefOut)] [InlineData("private int P { get { Error(); } set { Error(); } }", "", Match.RefOut)] // errors in methods bodies don't matter [InlineData("public int P { get; set; }", "", Match.Different)] [InlineData("protected int P { get; set; }", "", Match.Different)] [InlineData("private int P { get; set; }", "", Match.RefOut)] // private auto-property and underlying field are removed [InlineData("internal int P { get; set; }", "", Match.RefOut)] [InlineData("private event Action E { add { Error(); } remove { Error(); } }", "", Match.RefOut)] [InlineData("internal event Action E { add { Error(); } remove { Error(); } }", "", Match.RefOut)] [InlineData("private class C2 { }", "", Match.Different)] // all types are included [InlineData("private struct S { }", "", Match.Different)] [InlineData("public struct S { private int i; }", "public struct S { }", Match.Different)] [InlineData("private int i;", "", Match.RefOut)] [InlineData("public C() { }", "", Match.BothMetadataAndRefOut)] public void RefAssembly_InvariantToSomeChanges(string left, string right, Match expectedMatch) { string sourceTemplate = @" using System; public class C { CHANGE } "; CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: true); CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: false); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void RefAssembly_NoPia() { string piaSource = @" using System; using System.Runtime.InteropServices; [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [assembly: ImportedFromTypeLib(""Pia1.dll"")] public struct S { public int field; } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest1 { S M(); }"; var pia = CreateCompilation(piaSource, options: TestOptions.ReleaseDll, assemblyName: "pia"); pia.VerifyEmitDiagnostics(); string source = @" public class D : ITest1 { public S M() { throw null; } } "; var piaImageReference = pia.EmitToImageReference(embedInteropTypes: true); verifyRefOnly(piaImageReference); verifyRefOut(piaImageReference); var piaMetadataReference = pia.ToMetadataReference(embedInteropTypes: true); verifyRefOnly(piaMetadataReference); verifyRefOut(piaMetadataReference); void verifyRefOnly(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new MetadataReference[] { reference }); var refOnlyImage = EmitRefOnly(comp); verifyNoPia(refOnlyImage); } void verifyRefOut(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.DebugDll, references: new MetadataReference[] { reference }); var (image, refImage) = EmitRefOut(comp); verifyNoPia(image); verifyNoPia(refImage); } void verifyNoPia(ImmutableArray<byte> image) { var reference = CompilationVerifier.LoadTestEmittedExecutableForSymbolValidation(image, OutputKind.DynamicallyLinkedLibrary); var comp = CreateCompilation("", references: new[] { reference }); var referencedAssembly = comp.GetReferencedAssemblySymbol(reference); var module = (PEModuleSymbol)referencedAssembly.Modules[0]; var itest1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("ITest1"); Assert.NotNull(itest1.GetAttribute("System.Runtime.InteropServices", "TypeIdentifierAttribute")); var method = (PEMethodSymbol)itest1.GetMember("M"); Assert.Equal("S ITest1.M()", method.ToTestDisplayString()); var s = (NamedTypeSymbol)method.ReturnType; Assert.Equal("S", s.ToTestDisplayString()); Assert.NotNull(s.GetAttribute("System.Runtime.InteropServices", "TypeIdentifierAttribute")); var field = s.GetMember("field"); Assert.Equal("System.Int32 S.field", field.ToTestDisplayString()); } } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NoPiaNeedsDesktop)] public void RefAssembly_NoPia_ReferenceFromMethodBody() { string piaSource = @" using System; using System.Runtime.InteropServices; [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [assembly: ImportedFromTypeLib(""Pia1.dll"")] public struct S { public int field; } [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58280"")] public interface ITest1 { S M(); }"; var pia = CreateCompilation(piaSource, options: TestOptions.ReleaseDll, assemblyName: "pia"); pia.VerifyEmitDiagnostics(); string source = @" public class D { public void M2() { ITest1 x = null; S s = x.M(); } } "; var piaImageReference = pia.EmitToImageReference(embedInteropTypes: true); verifyRefOnly(piaImageReference); verifyRefOut(piaImageReference); var piaMetadataReference = pia.ToMetadataReference(embedInteropTypes: true); verifyRefOnly(piaMetadataReference); verifyRefOut(piaMetadataReference); void verifyRefOnly(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new MetadataReference[] { reference }); var refOnlyImage = EmitRefOnly(comp); verifyNoPia(refOnlyImage, expectMissing: true); } void verifyRefOut(MetadataReference reference) { var comp = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new MetadataReference[] { reference }); var (image, refImage) = EmitRefOut(comp); verifyNoPia(image, expectMissing: false); verifyNoPia(refImage, expectMissing: false); } // The ref assembly produced by refout has more types than that produced by refonly, // because refout will bind the method bodies (and therefore populate more referenced types). // This will be refined in the future. Follow-up issue: https://github.com/dotnet/roslyn/issues/19403 void verifyNoPia(ImmutableArray<byte> image, bool expectMissing) { var reference = CompilationVerifier.LoadTestEmittedExecutableForSymbolValidation(image, OutputKind.DynamicallyLinkedLibrary); var comp = CreateCompilation("", references: new[] { reference }); var referencedAssembly = comp.GetReferencedAssemblySymbol(reference); var module = (PEModuleSymbol)referencedAssembly.Modules[0]; var itest1 = module.GlobalNamespace.GetMember<NamedTypeSymbol>("ITest1"); if (expectMissing) { Assert.Null(itest1); Assert.Null(module.GlobalNamespace.GetMember<NamedTypeSymbol>("S")); return; } Assert.NotNull(itest1.GetAttribute("System.Runtime.InteropServices", "TypeIdentifierAttribute")); var method = (PEMethodSymbol)itest1.GetMember("M"); Assert.Equal("S ITest1.M()", method.ToTestDisplayString()); var s = (NamedTypeSymbol)method.ReturnType; Assert.Equal("S", s.ToTestDisplayString()); var field = s.GetMember("field"); Assert.Equal("System.Int32 S.field", field.ToTestDisplayString()); } } [Theory] [InlineData("internal void M() { }", "", Match.Different)] [InlineData("private protected void M() { }", "", Match.Different)] public void RefAssembly_InvariantToSomeChangesWithInternalsVisibleTo(string left, string right, Match expectedMatch) { string sourceTemplate = @" using System.Runtime.CompilerServices; [assembly: InternalsVisibleToAttribute(""Friend"")] public class C { CHANGE } "; CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: true); CompareAssemblies(sourceTemplate, left, right, expectedMatch, includePrivateMembers: false); } public enum Match { BothMetadataAndRefOut, RefOut, Different } /// <summary> /// Are the metadata-only assemblies identical with two source code modifications? /// Metadata-only assemblies can either include private/internal members or not. /// </summary> private static void CompareAssemblies(string sourceTemplate, string change1, string change2, Match expectedMatch, bool includePrivateMembers) { bool expectMatch = includePrivateMembers ? expectedMatch == Match.BothMetadataAndRefOut : (expectedMatch == Match.BothMetadataAndRefOut || expectedMatch == Match.RefOut); string name = GetUniqueName(); string source1 = sourceTemplate.Replace("CHANGE", change1); CSharpCompilation comp1 = CreateCompilation(Parse(source1), options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); var image1 = comp1.EmitToStream(EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(includePrivateMembers)); var source2 = sourceTemplate.Replace("CHANGE", change2); Compilation comp2 = CreateCompilation(Parse(source2), options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); var image2 = comp2.EmitToStream(EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(includePrivateMembers)); if (expectMatch) { AssertEx.Equal(image1.GetBuffer(), image2.GetBuffer(), message: $"Expecting match for includePrivateMembers={includePrivateMembers} case, but differences were found."); } else { AssertEx.NotEqual(image1.GetBuffer(), image2.GetBuffer(), message: $"Expecting difference for includePrivateMembers={includePrivateMembers} case, but they matched."); } var mvid1 = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(image1); var mvid2 = BuildTasks.MvidReader.ReadAssemblyMvidOrEmpty(image2); if (!includePrivateMembers) { Assert.NotEqual(Guid.Empty, mvid1); Assert.Equal(expectMatch, mvid1 == mvid2); } else { Assert.Equal(Guid.Empty, mvid1); Assert.Equal(Guid.Empty, mvid2); } } #if NET472 [ConditionalFact(typeof(DesktopOnly))] [WorkItem(31197, "https://github.com/dotnet/roslyn/issues/31197")] public void RefAssembly_InvariantToResourceChanges() { var arrayOfEmbeddedData1 = new byte[] { 1, 2, 3, 4, 5 }; var arrayOfEmbeddedData2 = new byte[] { 1, 2, 3, 4, 5, 6 }; IEnumerable<ResourceDescription> manifestResources1 = new[] { new ResourceDescription(resourceName: "A", fileName: "x.goo", () => new MemoryStream(arrayOfEmbeddedData1), isPublic: true)}; IEnumerable<ResourceDescription> manifestResources2 = new[] { new ResourceDescription(resourceName: "A", fileName: "x.goo", () => new MemoryStream(arrayOfEmbeddedData2), isPublic: true)}; verify(); manifestResources1 = new[] { new ResourceDescription(resourceName: "A", () => new MemoryStream(arrayOfEmbeddedData1), isPublic: true)}; // embedded manifestResources2 = new[] { new ResourceDescription(resourceName: "A", () => new MemoryStream(arrayOfEmbeddedData2), isPublic: true)}; // embedded verify(); void verify() { // Verify refout string name = GetUniqueName(); var (image1, metadataImage1) = emitRefOut(manifestResources1, name); var (image2, metadataImage2) = emitRefOut(manifestResources2, name); AssertEx.NotEqual(image1, image2, message: "Expecting different main assemblies produced by refout"); AssertEx.Equal(metadataImage1, metadataImage2, message: "Expecting identical ref assemblies produced by refout"); var refAssembly1 = Assembly.ReflectionOnlyLoad(metadataImage1.ToArray()); Assert.DoesNotContain("A", refAssembly1.GetManifestResourceNames()); // Verify refonly string name2 = GetUniqueName(); var refOnlyMetadataImage1 = emitRefOnly(manifestResources1, name2); var refOnlyMetadataImage2 = emitRefOnly(manifestResources2, name2); AssertEx.Equal(refOnlyMetadataImage1, refOnlyMetadataImage2, message: "Expecting identical ref assemblies produced by refonly"); var refOnlyAssembly1 = Assembly.ReflectionOnlyLoad(refOnlyMetadataImage1.ToArray()); Assert.DoesNotContain("A", refOnlyAssembly1.GetManifestResourceNames()); } (ImmutableArray<byte>, ImmutableArray<byte>) emitRefOut(IEnumerable<ResourceDescription> manifestResources, string name) { var source = Parse(""); var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); comp.VerifyDiagnostics(); var metadataPEStream = new MemoryStream(); var refoutOptions = EmitOptions.Default.WithEmitMetadataOnly(false).WithIncludePrivateMembers(false); var peStream = comp.EmitToArray(refoutOptions, metadataPEStream: metadataPEStream, manifestResources: manifestResources); return (peStream, metadataPEStream.ToImmutable()); } ImmutableArray<byte> emitRefOnly(IEnumerable<ResourceDescription> manifestResources, string name) { var source = Parse(""); var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); comp.VerifyDiagnostics(); var refonlyOptions = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); return comp.EmitToArray(refonlyOptions, metadataPEStream: null, manifestResources: manifestResources); } } #endif [Fact, WorkItem(31197, "https://github.com/dotnet/roslyn/issues/31197")] public void RefAssembly_CryptoHashFailedIsOnlyReportedOnce() { var hash_resources = new[] {new ResourceDescription("hash_resource", "snKey.snk", () => new MemoryStream(TestResources.General.snKey, writable: false), true)}; CSharpCompilation moduleComp = CreateEmptyCompilation("", options: TestOptions.DebugDll.WithDeterministic(true).WithOutputKind(OutputKind.NetModule)); var reference = ModuleMetadata.CreateFromImage(moduleComp.EmitToArray()).GetReference(); CSharpCompilation compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M() {} } ", references: new[] { reference }, options: TestOptions.ReleaseDll); // refonly var refonlyOptions = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); var refonlyDiagnostics = compilation.Emit(new MemoryStream(), pdbStream: null, options: refonlyOptions, manifestResources: hash_resources).Diagnostics; refonlyDiagnostics.Verify( // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); // refout var refoutOptions = EmitOptions.Default.WithEmitMetadataOnly(false).WithIncludePrivateMembers(false); var refoutDiagnostics = compilation.Emit(peStream: new MemoryStream(), metadataPEStream: new MemoryStream(), pdbStream: null, options: refoutOptions, manifestResources: hash_resources).Diagnostics; refoutDiagnostics.Verify( // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); } [Fact] public void RefAssemblyClient_RefReadonlyParameters() { VerifyRefAssemblyClient(@" public class C { public void RR_input(in int x) => throw null; public ref readonly int RR_output() => throw null; public ref readonly int P => throw null; public ref readonly int this[in int i] => throw null; public delegate ref readonly int Delegate(in int i); } public static class Extensions { public static void RR_extension(in this int x) => throw null; public static void R_extension(ref this int x) => throw null; }", @"class D { void M(C c, in int y) { c.RR_input(y); VerifyRR(c.RR_output()); VerifyRR(c.P); VerifyRR(c[y]); C.Delegate x = VerifyDelegate; y.RR_extension(); 1.RR_extension(); y.R_extension(); // error 1 1.R_extension(); // error 2 } void VerifyRR(in int y) => throw null; ref readonly int VerifyDelegate(in int y) => throw null; }", comp => comp.VerifyDiagnostics( // (12,9): error CS8329: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // y.R_extension(); // error 1 Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "y").WithArguments("variable", "in int").WithLocation(12, 9), // (13,9): error CS1510: A ref or out value must be an assignable variable // 1.R_extension(); // error 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(13, 9) )); } [Fact] public void RefAssemblyClient_StructWithPrivateReferenceTypeField() { VerifyRefAssemblyClient(@" public struct S { private object _field; public static S GetValue() => new S() { _field = new object() }; public object GetField() => _field; }", @"class C { void M() { unsafe { System.Console.WriteLine(sizeof(S*)); } } }", comp => comp.VerifyDiagnostics( // (7,45): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('S') // System.Console.WriteLine(sizeof(S*)); Diagnostic(ErrorCode.ERR_ManagedAddr, "S*").WithArguments("S").WithLocation(7, 45) )); } [Fact] public void RefAssemblyClient_ExplicitPropertyImplementation() { VerifyRefAssemblyClient(@" public interface I { int P { get; set; } } public class Base : I { int I.P { get { throw null; } set { throw null; } } }", @" class Derived : Base, I { }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitAllNestedTypes() { VerifyRefAssemblyClient(@" public interface I1<T> { } public interface I2 { } public class A: I1<A.X> { private class X: I2 { } }", @"class C { I1<I2> M(A a) { return (I1<I2>)a; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitTupleNames() { VerifyRefAssemblyClient(@" public class A { public (int first, int) field; }", @"class C { void M(A a) { System.Console.Write(a.field.first); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitDynamic() { VerifyRefAssemblyClient(@" public class A { public dynamic field; }", @"class C { void M(A a) { System.Console.Write(a.field.DynamicMethod()); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitOut() { VerifyRefAssemblyClient(@" public class A { public void M(out int x) { x = 1; } }", @"class C { void M(A a) { a.M(out int x); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitVariance_OutError() { VerifyRefAssemblyClient(@" public interface I<out T> { }", @" class Base { } class Derived : Base { I<Derived> M(I<Base> x) { return x; } }", comp => comp.VerifyDiagnostics( // (7,16): error CS0266: Cannot implicitly convert type 'I<Base>' to 'I<Derived>'. An explicit conversion exists (are you missing a cast?) // return x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("I<Base>", "I<Derived>").WithLocation(7, 16) )); } [Fact] public void RefAssemblyClient_EmitVariance_OutSuccess() { VerifyRefAssemblyClient(@" public interface I<out T> { }", @" class Base { } class Derived : Base { I<Base> M(I<Derived> x) { return x; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitVariance_InSuccess() { VerifyRefAssemblyClient(@" public interface I<in T> { }", @" class Base { } class Derived : Base { I<Derived> M(I<Base> x) { return x; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitVariance_InError() { VerifyRefAssemblyClient(@" public interface I<in T> { }", @" class Base { } class Derived : Base { I<Base> M(I<Derived> x) { return x; } }", comp => comp.VerifyDiagnostics( // (7,16): error CS0266: Cannot implicitly convert type 'I<Derived>' to 'I<Base>'. An explicit conversion exists (are you missing a cast?) // return x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("I<Derived>", "I<Base>").WithLocation(7, 16) )); } [Fact] public void RefAssemblyClient_EmitOptionalArguments() { VerifyRefAssemblyClient(@" public class A { public void M(int x = 42) { } }", @" class C { void M2(A a) { a.M(); } }", comp => { comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M2", @" { // Code size 11 (0xb) .maxstack 2 IL_0000: nop IL_0001: ldarg.1 IL_0002: ldc.i4.s 42 IL_0004: callvirt ""void A.M(int)"" IL_0009: nop IL_000a: ret }"); }); } [Fact] public void RefAssemblyClient_EmitArgumentNames() { VerifyRefAssemblyClient(@" public class Base { public virtual void M(int x) { } } public class Derived : Base { public override void M(int different) { } }", @" class C { void M2(Derived d) { d.M(different: 1); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitEnum() { VerifyRefAssemblyClient(@" public enum E { Default, Other }", @" class C { void M2(E e) { System.Console.Write(E.Other); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitConst() { VerifyRefAssemblyClient(@" public class A { public const int number = 42; }", @" class C { void M2() { System.Console.Write(A.number); } }", comp => { comp.VerifyDiagnostics(); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.M2", @" { // Code size 10 (0xa) .maxstack 1 IL_0000: nop IL_0001: ldc.i4.s 42 IL_0003: call ""void System.Console.Write(int)"" IL_0008: nop IL_0009: ret }"); }); } [Fact] public void RefAssemblyClient_EmitParams() { VerifyRefAssemblyClient(@" public class A { public void M(params int[] x) { } }", @" class C { void M2(A a) { a.M(1, 2, 3); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitExtension() { VerifyRefAssemblyClient(@" public static class A { public static void M(this string x) { } }", @" class C { void M2(string s) { s.M(); } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitAllTypes() { VerifyRefAssemblyClient(@" public interface I1<T> { } public interface I2 { } public class A: I1<X> { } internal class X: I2 { } ", @"class C { I1<I2> M(A a) { return (I1<I2>)a; } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_EmitNestedTypes() { VerifyRefAssemblyClient(@" public class A { public class Nested { } } ", @"class C { void M(A.Nested a) { } }", comp => comp.VerifyDiagnostics()); } [Fact] public void RefAssemblyClient_StructWithPrivateGenericField() { VerifyRefAssemblyClient(@" public struct Container<T> { private T contained; public void SetField(T value) { contained = value; } public T GetField() => contained; }", @"public struct Usage { public Container<Usage> x; }", comp => comp.VerifyDiagnostics( // (3,29): error CS0523: Struct member 'Usage.x' of type 'Container<Usage>' causes a cycle in the struct layout // public Container<Usage> x; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "x").WithArguments("Usage.x", "Container<Usage>").WithLocation(3, 29) )); } [Fact] public void RefAssemblyClient_EmitAllVirtualMethods() { var comp1 = CreateCSharpCompilation("CS1", @"[assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS2"")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo(""CS3"")] public abstract class C1 { internal abstract void M(); }", referencedAssemblies: new[] { MscorlibRef }); comp1.VerifyDiagnostics(); var image1 = comp1.EmitToImageReference(EmitOptions.Default); var comp2 = CreateCSharpCompilation("CS2", @"public abstract class C2 : C1 { internal override void M() { } }", referencedAssemblies: new[] { MscorlibRef, image1 }); var image2 = comp2.EmitToImageReference(EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)); // If internal virtual methods were not included in ref assemblies, then C3 could not be concrete and would report // error CS0534: 'C3' does not implement inherited abstract member 'C1.M()' var comp3 = CreateCSharpCompilation("CS3", @"public class C3 : C2 { }", referencedAssemblies: new[] { MscorlibRef, image1, image2 }); comp3.VerifyDiagnostics(); } [Fact] public void RefAssemblyClient_StructWithPrivateIntField() { VerifyRefAssemblyClient(@" public struct S { private int i; private void M() { System.Console.Write(i++); } }", @"class C { string M() { S s; return s.ToString(); } }", comp => comp.VerifyDiagnostics( // (6,16): error CS0165: Use of unassigned local variable 's' // return s.ToString(); Diagnostic(ErrorCode.ERR_UseDefViolation, "s").WithArguments("s").WithLocation(6, 16) )); } /// <summary> /// The client compilation should not be affected (except for some diagnostic differences) /// by the library assembly only having metadata, or not including private members. /// </summary> private void VerifyRefAssemblyClient(string lib_cs, string client_cs, Action<CSharpCompilation> validator, int debugFlag = -1) { // Whether the library is compiled in full, as metadata-only, or as a ref assembly should be transparent // to the client and the validator should be able to verify the same expectations. if (debugFlag == -1 || debugFlag == 0) { VerifyRefAssemblyClient(lib_cs, client_cs, validator, EmitOptions.Default.WithEmitMetadataOnly(false)); } if (debugFlag == -1 || debugFlag == 1) { VerifyRefAssemblyClient(lib_cs, client_cs, validator, EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(true)); } if (debugFlag == -1 || debugFlag == 2) { VerifyRefAssemblyClient(lib_cs, client_cs, validator, EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false)); } } private static void VerifyRefAssemblyClient(string lib_cs, string source, Action<CSharpCompilation> validator, EmitOptions emitOptions) { string name = GetUniqueName(); var libComp = CreateCompilation(lib_cs, options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); libComp.VerifyDiagnostics(); var libImage = libComp.EmitToImageReference(emitOptions); var comp = CreateCompilation(source, references: new[] { libImage }, options: TestOptions.DebugDll.WithAllowUnsafe(true)); validator(comp); } [Theory] [InlineData("", false)] [InlineData(@"[assembly: System.Reflection.AssemblyVersion(""1"")]", false)] [InlineData(@"[assembly: System.Reflection.AssemblyVersion(""1.0.0.*"")]", true)] public void RefAssembly_EmitAsDeterministic(string source, bool hasWildcard) { var name = GetUniqueName(); var options = TestOptions.DebugDll.WithDeterministic(false); var comp1 = CreateCompilation(source, options: options, assemblyName: name); var (out1, refOut1) = EmitRefOut(comp1); var refOnly1 = EmitRefOnly(comp1); VerifyIdentitiesMatch(out1, refOut1); VerifyIdentitiesMatch(out1, refOnly1); AssertEx.Equal(refOut1, refOut1); // The resolution of the PE header time date stamp is seconds (divided by two), and we want to make sure that has an opportunity to change // between calls to Emit. Thread.Sleep(TimeSpan.FromSeconds(3)); // Re-using the same compilation results in the same time stamp var (out15, refOut15) = EmitRefOut(comp1); VerifyIdentitiesMatch(out1, out15); VerifyIdentitiesMatch(refOut1, refOut15); AssertEx.Equal(refOut1, refOut15); // Using a new compilation results in new time stamp var comp2 = CreateCompilation(source, options: options, assemblyName: name); var (out2, refOut2) = EmitRefOut(comp2); var refOnly2 = EmitRefOnly(comp2); VerifyIdentitiesMatch(out2, refOut2); VerifyIdentitiesMatch(out2, refOnly2); VerifyIdentitiesMatch(out1, out2, expectMatch: !hasWildcard); VerifyIdentitiesMatch(refOut1, refOut2, expectMatch: !hasWildcard); if (hasWildcard) { AssertEx.NotEqual(refOut1, refOut2); AssertEx.NotEqual(refOut1, refOnly2); } else { // If no wildcards, the binaries are emitted deterministically AssertEx.Equal(refOut1, refOut2); AssertEx.Equal(refOut1, refOnly2); } } private void VerifySigned(ImmutableArray<byte> image, bool expectSigned = true) { using (var reader = new PEReader(image)) { var flags = reader.PEHeaders.CorHeader.Flags; Assert.Equal(expectSigned, flags.HasFlag(CorFlags.StrongNameSigned)); } } private static void VerifyIdentitiesMatch(ImmutableArray<byte> firstImage, ImmutableArray<byte> secondImage, bool expectMatch = true, bool expectPublicKey = false) { var id1 = ModuleMetadata.CreateFromImage(firstImage).GetMetadataReader().ReadAssemblyIdentityOrThrow(); var id2 = ModuleMetadata.CreateFromImage(secondImage).GetMetadataReader().ReadAssemblyIdentityOrThrow(); Assert.Equal(expectMatch, id1 == id2); if (expectPublicKey) { Assert.True(id1.HasPublicKey); Assert.True(id2.HasPublicKey); } } private static (ImmutableArray<byte> image, ImmutableArray<byte> refImage) EmitRefOut(CSharpCompilation comp) { using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { var options = EmitOptions.Default.WithIncludePrivateMembers(false); comp.VerifyEmitDiagnostics(); var result = comp.Emit(output, metadataPEStream: metadataOutput, options: options); return (output.ToImmutable(), metadataOutput.ToImmutable()); } } private static ImmutableArray<byte> EmitRefOnly(CSharpCompilation comp) { using (var output = new MemoryStream()) { var options = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); comp.VerifyEmitDiagnostics(); var result = comp.Emit(output, options: options); return output.ToImmutable(); } } [Fact] public void RefAssembly_PublicSigning() { var snk = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey); var comp = CreateCompilation("public class C{}", options: TestOptions.ReleaseDll.WithCryptoKeyFile(snk.Path).WithPublicSign(true)); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image); VerifySigned(refImage); VerifySigned(refOnlyImage); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Fact] public void RefAssembly_StrongNameProvider() { var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile); var comp = CreateCompilation("public class C{}", options: signedDllOptions); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image); VerifySigned(refImage); VerifySigned(refOnlyImage); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Fact] public void RefAssembly_StrongNameProvider_Arm64() { var signedDllOptions = TestOptions.SigningReleaseDll. WithCryptoKeyFile(SigningTestHelpers.KeyPairFile). WithPlatform(Platform.Arm64). WithDeterministic(true); var comp = CreateCompilation("public class C{}", options: signedDllOptions); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image); VerifySigned(refImage); VerifySigned(refOnlyImage); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Fact] public void RefAssembly_StrongNameProviderAndDelaySign() { var signedDllOptions = TestOptions.SigningReleaseDll .WithCryptoKeyFile(SigningTestHelpers.KeyPairFile) .WithDelaySign(true); var comp = CreateCompilation("public class C{}", options: signedDllOptions); comp.VerifyDiagnostics(); var (image, refImage) = EmitRefOut(comp); var refOnlyImage = EmitRefOnly(comp); VerifySigned(image, expectSigned: false); VerifySigned(refImage, expectSigned: false); VerifySigned(refOnlyImage, expectSigned: false); VerifyIdentitiesMatch(image, refImage, expectPublicKey: true); VerifyIdentitiesMatch(image, refOnlyImage, expectPublicKey: true); } [Theory] [InlineData("public int M() { error(); }", true)] [InlineData("public int M() { error() }", false)] // This may get relaxed. See follow-up issue https://github.com/dotnet/roslyn/issues/17612 [InlineData("public int M();", true)] [InlineData("public int M() { int Local(); }", true)] [InlineData("public C();", true)] [InlineData("~ C();", true)] [InlineData("public Error M() { return null; }", false)] // This may get relaxed. See follow-up issue https://github.com/dotnet/roslyn/issues/17612 [InlineData("public static explicit operator C(int i);", true)] [InlineData("public async Task M();", false)] [InlineData("partial void M(); partial void M();", false)] // This may get relaxed. See follow-up issue https://github.com/dotnet/roslyn/issues/17612 public void RefAssembly_IgnoresSomeDiagnostics(string change, bool expectSuccess) { string sourceTemplate = @" using System.Threading.Tasks; public partial class C { CHANGE } "; VerifyIgnoresDiagnostics(EmitOptions.Default.WithEmitMetadataOnly(false).WithTolerateErrors(false), success: false); VerifyIgnoresDiagnostics(EmitOptions.Default.WithEmitMetadataOnly(true).WithTolerateErrors(false), success: expectSuccess); void VerifyIgnoresDiagnostics(EmitOptions emitOptions, bool success) { string source = sourceTemplate.Replace("CHANGE", change); string name = GetUniqueName(); CSharpCompilation comp = CreateCompilation(Parse(source), options: TestOptions.DebugDll.WithDeterministic(true), assemblyName: name); using (var output = new MemoryStream()) { var emitResult = comp.Emit(output, options: emitOptions); Assert.Equal(!success, emitResult.Diagnostics.HasAnyErrors()); Assert.Equal(success, emitResult.Success); } } } [Fact] public void RefAssembly_VerifyTypesAndMembers() { string source = @" public class PublicClass { public void PublicMethod() { System.Console.Write(new { anonymous = 1 }); } private void PrivateMethod() { System.Console.Write(""Hello""); } protected void ProtectedMethod() { System.Console.Write(""Hello""); } internal void InternalMethod() { System.Console.Write(""Hello""); } protected internal void ProtectedInternalMethod() { } private protected void PrivateProtectedMethod() { } public event System.Action PublicEvent; internal event System.Action InternalEvent; } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, parseOptions: TestOptions.Regular7_2, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "<>f__AnonymousType0<<anonymous>j__TPar>", "PublicClass" }, compWithReal.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.PrivateMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.InternalMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PrivateProtectedMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "void PublicClass.InternalEvent.add", "void PublicClass.InternalEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent", "event System.Action PublicClass.InternalEvent" }, compWithReal.GetMember<NamedTypeSymbol>("PublicClass").GetMembers() .Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute" }, compWithReal.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); // Verify metadata (types, members, attributes) of the regular assembly with IncludePrivateMembers accidentally set to false. // Note this can happen because of binary clients compiled against old EmitOptions ctor which had IncludePrivateMembers=false by default. // In this case, IncludePrivateMembers is silently set to true when emitting // See https://github.com/dotnet/roslyn/issues/20873 var emitRegularWithoutPrivateMembers = EmitOptions.Default.WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRegularWithoutPrivateMembers, verify: Verification.Passes); var realImage2 = comp.EmitToImageReference(emitRegularWithoutPrivateMembers); var compWithReal2 = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage2 }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "<>f__AnonymousType0<<anonymous>j__TPar>", "PublicClass" }, compWithReal2.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.PrivateMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.InternalMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PrivateProtectedMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "void PublicClass.InternalEvent.add", "void PublicClass.InternalEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent", "event System.Action PublicClass.InternalEvent" }, compWithReal2.GetMember<NamedTypeSymbol>("PublicClass").GetMembers() .Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute" }, compWithReal2.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "PublicClass" }, compWithMetadata.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.PrivateMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.InternalMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PrivateProtectedMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "void PublicClass.InternalEvent.add", "void PublicClass.InternalEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent", "event System.Action PublicClass.InternalEvent" }, compWithMetadata.GetMember<NamedTypeSymbol>("PublicClass").GetMembers().Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute" }, compWithMetadata.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "PublicClass" }, compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void PublicClass.PublicMethod()", "void PublicClass.ProtectedMethod()", "void PublicClass.ProtectedInternalMethod()", "void PublicClass.PublicEvent.add", "void PublicClass.PublicEvent.remove", "PublicClass..ctor()", "event System.Action PublicClass.PublicEvent"}, compWithRef.GetMember<NamedTypeSymbol>("PublicClass").GetMembers().Select(m => m.ToTestDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.CompilationRelaxationsAttribute", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute", "System.Diagnostics.DebuggableAttribute", "System.Runtime.CompilerServices.ReferenceAssemblyAttribute" }, compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GetAttributes().Select(a => a.AttributeClass.ToTestDisplayString())); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); } [Fact] public void RefAssembly_VerifyTypesAndMembersOnExplicitlyImplementedProperty() { string source = @" public interface I { int P { get; set; } } public class C : I { int I.P { get { throw null; } set { throw null; } } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyPropertyWasEmitted(compWithReal); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyPropertyWasEmitted(compWithMetadata); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyPropertyWasEmitted(compWithRef); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); void verifyPropertyWasEmitted(CSharpCompilation input) { AssertEx.Equal( new[] { "<Module>", "I", "C" }, input.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Int32 C.I.P.get", "void C.I.P.set", "C..ctor()", "System.Int32 C.I.P { get; set; }" }, input.GetMember<NamedTypeSymbol>("C").GetMembers() .Select(m => m.ToTestDisplayString())); } } [Fact] public void RefAssembly_VerifyTypesAndMembersOnExplicitlyImplementedEvent() { string source = @" public interface I { event System.Action E; } public class C : I { event System.Action I.E { add { throw null; } remove { throw null; } } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyEventWasEmitted(compWithReal); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyEventWasEmitted(compWithMetadata); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyEventWasEmitted(compWithRef); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); void verifyEventWasEmitted(CSharpCompilation input) { AssertEx.Equal( new[] { "<Module>", "I", "C" }, input.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "void C.I.E.add", "void C.I.E.remove", "C..ctor()", "event System.Action C.I.E" }, input.GetMember<NamedTypeSymbol>("C").GetMembers() .Select(m => m.ToTestDisplayString())); } } [Fact] public void RefAssembly_VerifyTypesAndMembersOnExplicitlyImplementedIndexer() { string source = @" public interface I { int this[int i] { get; set; } } public class C : I { int I.this[int i] { get { throw null; } set { throw null; } } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the regular assembly CompileAndVerify(comp, emitOptions: EmitOptions.Default, verify: Verification.Passes); var realImage = comp.EmitToImageReference(EmitOptions.Default); var compWithReal = CreateEmptyCompilation("", references: new[] { MscorlibRef, realImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyIndexerWasEmitted(compWithReal); // verify metadata (types, members, attributes) of the metadata-only assembly var emitMetadataOnly = EmitOptions.Default.WithEmitMetadataOnly(true); CompileAndVerify(comp, emitOptions: emitMetadataOnly, verify: Verification.Passes); var metadataImage = comp.EmitToImageReference(emitMetadataOnly); var compWithMetadata = CreateEmptyCompilation("", references: new[] { MscorlibRef, metadataImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyIndexerWasEmitted(compWithMetadata); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitMetadataOnly)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); verifyIndexerWasEmitted(compWithRef); MetadataReaderUtils.AssertEmptyOrThrowNull(comp.EmitToArray(emitRefOnly)); void verifyIndexerWasEmitted(CSharpCompilation input) { AssertEx.Equal( new[] { "<Module>", "I", "C" }, input.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] {"System.Int32 C.I.get_Item(System.Int32 i)", "void C.I.set_Item(System.Int32 i, System.Int32 value)", "C..ctor()", "System.Int32 C.I.Item[System.Int32 i] { get; set; }" }, input.GetMember<NamedTypeSymbol>("C").GetMembers() .Select(m => m.ToTestDisplayString())); } } [Fact] public void RefAssembly_VerifyTypesAndMembersOnStruct() { string source = @" internal struct InternalStruct { internal int P { get; set; } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); var globalNamespace = compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace; AssertEx.Equal( new[] { "<Module>", "InternalStruct", "Microsoft", "System" }, globalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal(new[] { "Microsoft.CodeAnalysis" }, globalNamespace.GetMember<NamespaceSymbol>("Microsoft").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "Microsoft.CodeAnalysis.EmbeddedAttribute" }, globalNamespace.GetMember<NamespaceSymbol>("Microsoft.CodeAnalysis").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices" }, globalNamespace.GetMember<NamespaceSymbol>("System.Runtime").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Runtime.CompilerServices.IsReadOnlyAttribute" }, globalNamespace.GetMember<NamespaceSymbol>("System.Runtime.CompilerServices").GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "System.Int32 InternalStruct.<P>k__BackingField", "InternalStruct..ctor()" }, compWithRef.GetMember<NamedTypeSymbol>("InternalStruct").GetMembers().Select(m => m.ToTestDisplayString())); } [Fact] public void RefAssembly_VerifyTypesAndMembersOnPrivateStruct() { string source = @" struct S { private class PrivateType { } private PrivateType field; } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); // verify metadata (types, members, attributes) of the ref assembly var emitRefOnly = EmitOptions.Default.WithEmitMetadataOnly(true).WithIncludePrivateMembers(false); CompileAndVerify(comp, emitOptions: emitRefOnly, verify: Verification.Passes); var refImage = comp.EmitToImageReference(emitRefOnly); var compWithRef = CreateEmptyCompilation("", references: new[] { MscorlibRef, refImage }, options: TestOptions.DebugDll.WithMetadataImportOptions(MetadataImportOptions.All)); AssertEx.Equal( new[] { "<Module>", "S" }, compWithRef.SourceModule.GetReferencedAssemblySymbols().Last().GlobalNamespace.GetMembers().Select(m => m.ToDisplayString())); AssertEx.Equal( new[] { "S.PrivateType S.field", "S..ctor()", "S.PrivateType" }, compWithRef.GetMember<NamedTypeSymbol>("S").GetMembers().Select(m => m.ToTestDisplayString())); } [Fact] public void EmitMetadataOnly_DisallowPdbs() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var pdbOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, pdbOutput, options: EmitOptions.Default.WithEmitMetadataOnly(true))); } } [Fact] public void EmitMetadataOnly_DisallowMetadataPeStream() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var metadataPeOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, metadataPEStream: metadataPeOutput, options: EmitOptions.Default.WithEmitMetadataOnly(true))); } } [Fact] public void IncludePrivateMembers_DisallowMetadataPeStream() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var metadataPeOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, metadataPEStream: metadataPeOutput, options: EmitOptions.Default.WithIncludePrivateMembers(true))); } } [Fact] [WorkItem(20873, "https://github.com/dotnet/roslyn/issues/20873")] public void IncludePrivateMembersSilentlyAssumedTrueWhenEmittingRegular() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) { // no exception _ = comp.Emit(output, options: EmitOptions.Default.WithIncludePrivateMembers(false)); } } [Fact] public void EmitMetadata_DisallowOutputtingNetModule() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true).WithOutputKind(OutputKind.NetModule)); using (var output = new MemoryStream()) using (var metadataPeOutput = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, metadataPEStream: metadataPeOutput, options: EmitOptions.Default)); } } [Fact] public void EmitMetadataOnly_DisallowOutputtingNetModule() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true).WithOutputKind(OutputKind.NetModule)); using (var output = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, options: EmitOptions.Default.WithEmitMetadataOnly(true))); } } [Fact] public void RefAssembly_AllowEmbeddingPdb() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll); using (var output = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { var result = comp.Emit(output, metadataPEStream: metadataOutput, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded).WithIncludePrivateMembers(false)); VerifyEmbeddedDebugInfo(output, new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }); VerifyEmbeddedDebugInfo(metadataOutput, new DebugDirectoryEntryType[] { DebugDirectoryEntryType.Reproducible }); } void VerifyEmbeddedDebugInfo(MemoryStream stream, DebugDirectoryEntryType[] expected) { using (var peReader = new PEReader(stream.ToImmutable())) { var entries = peReader.ReadDebugDirectory(); AssertEx.Equal(expected, entries.Select(e => e.Type)); } } } [Fact] public void EmitMetadataOnly_DisallowEmbeddingPdb() { CSharpCompilation comp = CreateEmptyCompilation("", references: new[] { MscorlibRef }, options: TestOptions.DebugDll); using (var output = new MemoryStream()) { Assert.Throws<ArgumentException>(() => comp.Emit(output, options: EmitOptions.Default.WithEmitMetadataOnly(true) .WithDebugInformationFormat(DebugInformationFormat.Embedded))); } } [Fact] public void EmitMetadata() { string source = @" public abstract class PublicClass { public void PublicMethod() { System.Console.Write(""Hello""); } } "; CSharpCompilation comp = CreateEmptyCompilation(source, references: new[] { MscorlibRef }, options: TestOptions.DebugDll.WithDeterministic(true)); using (var output = new MemoryStream()) using (var pdbOutput = new MemoryStream()) using (var metadataOutput = new MemoryStream()) { var result = comp.Emit(output, pdbOutput, metadataPEStream: metadataOutput); Assert.True(result.Success); Assert.NotEqual(0, output.Position); Assert.NotEqual(0, pdbOutput.Position); Assert.NotEqual(0, metadataOutput.Position); MetadataReaderUtils.AssertNotThrowNull(ImmutableArray.CreateRange(output.GetBuffer())); MetadataReaderUtils.AssertEmptyOrThrowNull(ImmutableArray.CreateRange(metadataOutput.GetBuffer())); } var peImage = comp.EmitToArray(); MetadataReaderUtils.AssertNotThrowNull(peImage); } /// <summary> /// Check that when we emit metadata only, we include metadata for /// compiler generate methods (e.g. the ones for implicit interface /// implementation). /// </summary> [Fact] public void EmitMetadataOnly_SynthesizedExplicitImplementations() { var ilAssemblyReference = TestReferences.SymbolsTests.CustomModifiers.CppCli.dll; var libAssemblyName = "SynthesizedMethodMetadata"; var exeAssemblyName = "CallSynthesizedMethod"; // Setup: CppBase2 has methods that implement CppInterface1, but it doesn't declare // that it implements the interface. Class1 does declare that it implements the // interface, but it's empty so it counts on CppBase2 to provide the implementations. // Since CppBase2 is not in the current source module, bridge methods are inserted // into Class1 to implement the interface methods by delegating to CppBase2. var libText = @" public class Class1 : CppCli.CppBase2, CppCli.CppInterface1 { } "; var libComp = CreateCompilation( source: libText, references: new MetadataReference[] { ilAssemblyReference }, options: TestOptions.ReleaseDll, assemblyName: libAssemblyName); Assert.False(libComp.GetDiagnostics().Any()); EmitResult emitResult; byte[] dllImage; using (var output = new MemoryStream()) { emitResult = libComp.Emit(output, options: new EmitOptions(metadataOnly: true)); dllImage = output.ToArray(); } Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); Assert.True(dllImage.Length > 0, "no metadata emitted"); // NOTE: this DLL won't PEVerify because there are no method bodies. var class1 = libComp.GlobalNamespace.GetMember<SourceNamedTypeSymbol>("Class1"); // We would prefer to check that the module used by Compiler.Emit does the right thing, // but we don't have access to that object, so we'll create our own and manipulate it // in the same way. var module = new PEAssemblyBuilder((SourceAssemblySymbol)class1.ContainingAssembly, EmitOptions.Default, OutputKind.DynamicallyLinkedLibrary, GetDefaultModulePropertiesForSerialization(), SpecializedCollections.EmptyEnumerable<ResourceDescription>()); SynthesizedMetadataCompiler.ProcessSynthesizedMembers(libComp, module, default(CancellationToken)); var class1TypeDef = (Cci.ITypeDefinition)class1.GetCciAdapter(); var symbolSynthesized = class1.GetSynthesizedExplicitImplementations(CancellationToken.None).ForwardingMethods; var context = new EmitContext(module, null, new DiagnosticBag(), metadataOnly: false, includePrivateMembers: true); var cciExplicit = class1TypeDef.GetExplicitImplementationOverrides(context); var cciMethods = class1TypeDef.GetMethods(context).Where(m => ((MethodSymbol)m.GetInternalSymbol()).MethodKind != MethodKind.Constructor); context.Diagnostics.Verify(); var symbolsSynthesizedCount = symbolSynthesized.Length; Assert.True(symbolsSynthesizedCount > 0, "Expected more than 0 synthesized method symbols."); Assert.Equal(symbolsSynthesizedCount, cciExplicit.Count()); Assert.Equal(symbolsSynthesizedCount, cciMethods.Count()); var libAssemblyReference = MetadataReference.CreateFromImage(dllImage.AsImmutableOrNull()); var exeText = @" class Class2 { public static void Main() { CppCli.CppInterface1 c = new Class1(); c.Method1(1); c.Method2(2); } } "; var exeComp = CreateCompilation( source: exeText, references: new MetadataReference[] { ilAssemblyReference, libAssemblyReference }, assemblyName: exeAssemblyName); Assert.False(exeComp.GetDiagnostics().Any()); using (var output = new MemoryStream()) { emitResult = exeComp.Emit(output); Assert.True(emitResult.Success); emitResult.Diagnostics.Verify(); output.Flush(); Assert.True(output.Length > 0, "no metadata emitted"); } // NOTE: there's no point in trying to run the EXE since it depends on a DLL with no method bodies. } [WorkItem(539982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539982")] [Fact] public void EmitNestedLambdaWithAddPlusOperator() { CompileAndVerify(@" public class C { delegate int D(int i); delegate D E(int i); public static void Main() { D y = x => x + 1; E e = x => (y += (z => z + 1)); } } "); } [Fact, WorkItem(539983, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539983")] public void EmitAlwaysFalseExpression() { CompileAndVerify(@" class C { static bool Goo(int i) { int y = 10; bool x = (y == null); // NYI: Implicit null conversion return x; } } "); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void EmitLambdaInConstructorInitializer() { string source = @" using System; public class A { public A(string x):this(()=>x) {} public A(Func<string> x) { Console.WriteLine(x()); } static void Main() { A a = new A(""Hello""); } }"; CompileAndVerify(source, expectedOutput: "Hello"); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void EmitLambdaInConstructorBody() { string source = @" using System; public class A { public string y = ""!""; public A(string x) {func(()=>x+y); } public A(Func<string> x) { Console.WriteLine(x()); } public void func(Func<string> x) { Console.WriteLine(x()); } static void Main() { A a = new A(""Hello""); } }"; CompileAndVerify(source, expectedOutput: "Hello!"); } [WorkItem(540146, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540146")] [Fact] public void EmitLambdaInConstructorInitializerAndBody() { string source = @" using System; public class A { public string y = ""!""; public A(string x):this(()=>x){func(()=>x+y);} public A(Func<string> x) { Console.WriteLine(x()); } public void func (Func<string> x) { Console.WriteLine(x()); } static void Main() { A a = new A(""Hello""); } }"; CompileAndVerify(source, expectedOutput: @" Hello Hello! "); } [WorkItem(541786, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541786")] [Fact] public void EmitInvocationExprInIfStatementNestedInsideCatch() { string source = @" static class Test { static public void Main() { int i1 = 45; try { } catch { if (i1.ToString() == null) { } } System.Console.WriteLine(i1); } }"; CompileAndVerify(source, expectedOutput: "45"); } [WorkItem(541822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541822")] [Fact] public void EmitSwitchOnByteType() { string source = @" using System; public class Test { public static object TestSwitch(byte val) { switch (val) { case (byte)0: return 0; case (byte)1: return 1; case (byte)0x7F: return (byte)0x7F; case (byte)0xFE: return (byte)0xFE; case (byte)0xFF: return (byte)0xFF; default: return null; } } public static void Main() { Console.WriteLine(TestSwitch(0)); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541823, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541823")] [Fact] public void EmitSwitchOnIntTypeBoundary() { string source = @" public class Test { public static object TestSwitch(int val) { switch (val) { case (int)int.MinValue: case (int)int.MinValue + 1: case (int)short.MinValue: case (int)short.MinValue + 1: case (int)sbyte.MinValue: return 0; case (int)-1: return -1; case (int)0: return 0; case (int)1: return 0; case (int)0x7F: return 0; case (int)0xFE: return 0; case (int)0xFF: return 0; case (int)0x7FFE: return 0; case (int)0xFFFE: case (int)0x7FFFFFFF: return 0; default: return null; } } public static void Main() { System.Console.WriteLine(TestSwitch(-1)); } } "; CompileAndVerify(source, expectedOutput: "-1"); } [WorkItem(541824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541824")] [Fact] public void EmitSwitchOnLongTypeBoundary() { string source = @" public class Test { public static object TestSwitch(long val) { switch (val) { case (long)long.MinValue: return (long)long.MinValue; case (long)long.MinValue + 1: return (long)long.MinValue + 1; case (long)int.MinValue: return (long)int.MinValue; case (long)int.MinValue + 1: return (long)int.MinValue + 1; case (long)short.MinValue: return (long)short.MinValue; case (long)short.MinValue + 1: return (long)short.MinValue + 1; case (long)sbyte.MinValue: return (long)sbyte.MinValue; case (long)-1: return (long)-1; case (long)0: return (long)0; case (long)1: return (long)1; case (long)0x7F: return (long)0x7F; case (long)0xFE: return (long)0xFE; case (long)0xFF: return (long)0xFF; case (long)0x7FFE: return (long)0x7FFE; case (long)0x7FFF: return (long)0x7FFF; case (long)0xFFFE: return (long)0xFFFE; case (long)0xFFFF: return (long)0xFFFF; case (long)0x7FFFFFFE: return (long)0x7FFFFFFE; case (long)0x7FFFFFFF: return (long)0x7FFFFFFF; case (long)0xFFFFFFFE: return (long)0xFFFFFFFE; case (long)0xFFFFFFFF: return (long)0xFFFFFFFF; case (long)0x7FFFFFFFFFFFFFFE: return (long)0x7FFFFFFFFFFFFFFE; case (long)0x7FFFFFFFFFFFFFFF: return (long)0x7FFFFFFFFFFFFFFF; default: return null; } } public static void Main() { System.Console.WriteLine(TestSwitch(0)); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnLongTypeBoundary2() { string source = @" public class Test { private static int DoLong() { int ret = 2; long l = 0x7fffffffffffffffL; switch (l) { case 1L: case 9223372036854775807L: ret--; break; case -1L: break; default: break; } switch (l) { case 1L: case -1L: break; default: ret--; break; } return (ret); } public static void Main(string[] args) { System.Console.WriteLine(DoLong()); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnLongTypeBoundary3() { string source = @" public class Test { public static object TestSwitch(long val) { switch (val) { case (long)long.MinValue: return (long)long.MinValue; case (long)long.MinValue + 1: return (long)long.MinValue + 1; case (long)int.MinValue: return (long)int.MinValue; case (long)int.MinValue + 1: return (long)int.MinValue + 1; case (long)short.MinValue: return (long)short.MinValue; case (long)short.MinValue + 1: return (long)short.MinValue + 1; case (long)sbyte.MinValue: return (long)sbyte.MinValue; case (long)-1: return (long)-1; case (long)0: return (long)0; case (long)1: return (long)1; case (long)0x7F: return (long)0x7F; case (long)0xFE: return (long)0xFE; case (long)0xFF: return (long)0xFF; case (long)0x7FFE: return (long)0x7FFE; case (long)0x7FFF: return (long)0x7FFF; case (long)0xFFFE: return (long)0xFFFE; case (long)0xFFFF: return (long)0xFFFF; case (long)0x7FFFFFFE: return (long)0x7FFFFFFE; case (long)0x7FFFFFFF: return (long)0x7FFFFFFF; case (long)0xFFFFFFFE: return (long)0xFFFFFFFE; case (long)0xFFFFFFFF: return (long)0xFFFFFFFF; case (long)0x7FFFFFFFFFFFFFFE: return (long)0x7FFFFFFFFFFFFFFE; case (long)0x7FFFFFFFFFFFFFFF: return (long)0x7FFFFFFFFFFFFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((long)long.MinValue).Equals(TestSwitch(long.MinValue))); b1 = b1 && (((long)long.MinValue + 1).Equals(TestSwitch(long.MinValue + 1))); b1 = b1 && (((long)int.MinValue).Equals(TestSwitch(int.MinValue))); b1 = b1 && (((long)int.MinValue + 1).Equals(TestSwitch(int.MinValue + 1))); b1 = b1 && (((long)short.MinValue).Equals(TestSwitch(short.MinValue))); b1 = b1 && (((long)short.MinValue + 1).Equals(TestSwitch(short.MinValue + 1))); b1 = b1 && (((long)sbyte.MinValue).Equals(TestSwitch(sbyte.MinValue))); b1 = b1 && (((long)-1).Equals(TestSwitch(-1))); b1 = b1 && (((long)0).Equals(TestSwitch(0))); b1 = b1 && (((long)1).Equals(TestSwitch(1))); b1 = b1 && (((long)0x7F).Equals(TestSwitch(0x7F))); b1 = b1 && (((long)0xFE).Equals(TestSwitch(0xFE))); b1 = b1 && (((long)0xFF).Equals(TestSwitch(0xFF))); b1 = b1 && (((long)0x7FFE).Equals(TestSwitch(0x7FFE))); b1 = b1 && (((long)0x7FFF).Equals(TestSwitch(0x7FFF))); b1 = b1 && (((long)0xFFFE).Equals(TestSwitch(0xFFFE))); b1 = b1 && (((long)0xFFFF).Equals(TestSwitch(0xFFFF))); b1 = b1 && (((long)0x7FFFFFFE).Equals(TestSwitch(0x7FFFFFFE))); b1 = b1 && (((long)0x7FFFFFFF).Equals(TestSwitch(0x7FFFFFFF))); b1 = b1 && (((long)0xFFFFFFFE).Equals(TestSwitch(0xFFFFFFFE))); b1 = b1 && (((long)0xFFFFFFFF).Equals(TestSwitch(0xFFFFFFFF))); b1 = b1 && (((long)0x7FFFFFFFFFFFFFFE).Equals(TestSwitch(0x7FFFFFFFFFFFFFFE))); b1 = b1 && (((long)0x7FFFFFFFFFFFFFFF).Equals(TestSwitch(0x7FFFFFFFFFFFFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnCharTypeBoundary() { string source = @" public class Test { public static object TestSwitch(char val) { switch (val) { case (char)0: return (char)0; case (char)1: return (char)1; case (char)0x7F: return (char)0x7F; case (char)0xFE: return (char)0xFE; case (char)0xFF: return (char)0xFF; case (char)0x7FFE: return (char)0x7FFE; case (char)0x7FFF: return (char)0x7FFF; case (char)0xFFFE: return (char)0xFFFE; case (char)0xFFFF: return (char)0xFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((char)0).Equals(TestSwitch((char)0))); b1 = b1 && (((char)1).Equals(TestSwitch((char)1))); b1 = b1 && (((char)0x7F).Equals(TestSwitch((char)0x7F))); b1 = b1 && (((char)0xFE).Equals(TestSwitch((char)0xFE))); b1 = b1 && (((char)0xFF).Equals(TestSwitch((char)0xFF))); b1 = b1 && (((char)0x7FFE).Equals(TestSwitch((char)0x7FFE))); b1 = b1 && (((char)0x7FFF).Equals(TestSwitch((char)0x7FFF))); b1 = b1 && (((char)0xFFFE).Equals(TestSwitch((char)0xFFFE))); b1 = b1 && (((char)0xFFFF).Equals(TestSwitch((char)0xFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541840")] [Fact] public void EmitSwitchOnUIntTypeBoundary() { string source = @" public class Test { public static object TestSwitch(uint val) { switch (val) { case (uint)0: return (uint)0; case (uint)1: return (uint)1; case (uint)0x7F: return (uint)0x7F; case (uint)0xFE: return (uint)0xFE; case (uint)0xFF: return (uint)0xFF; case (uint)0x7FFE: return (uint)0x7FFE; case (uint)0x7FFF: return (uint)0x7FFF; case (uint)0xFFFE: return (uint)0xFFFE; case (uint)0xFFFF: return (uint)0xFFFF; case (uint)0x7FFFFFFE: return (uint)0x7FFFFFFE; case (uint)0x7FFFFFFF: return (uint)0x7FFFFFFF; case (uint)0xFFFFFFFE: return (uint)0xFFFFFFFE; case (uint)0xFFFFFFFF: return (uint)0xFFFFFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((uint)0).Equals(TestSwitch(0))); b1 = b1 && (((uint)1).Equals(TestSwitch(1))); b1 = b1 && (((uint)0x7F).Equals(TestSwitch(0x7F))); b1 = b1 && (((uint)0xFE).Equals(TestSwitch(0xFE))); b1 = b1 && (((uint)0xFF).Equals(TestSwitch(0xFF))); b1 = b1 && (((uint)0x7FFE).Equals(TestSwitch(0x7FFE))); b1 = b1 && (((uint)0x7FFF).Equals(TestSwitch(0x7FFF))); b1 = b1 && (((uint)0xFFFE).Equals(TestSwitch(0xFFFE))); b1 = b1 && (((uint)0xFFFF).Equals(TestSwitch(0xFFFF))); b1 = b1 && (((uint)0x7FFFFFFE).Equals(TestSwitch(0x7FFFFFFE))); b1 = b1 && (((uint)0x7FFFFFFF).Equals(TestSwitch(0x7FFFFFFF))); b1 = b1 && (((uint)0xFFFFFFFE).Equals(TestSwitch(0xFFFFFFFE))); b1 = b1 && (((uint)0xFFFFFFFF).Equals(TestSwitch(0xFFFFFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541824")] [Fact] public void EmitSwitchOnUnsignedLongTypeBoundary() { string source = @" public class Test { public static object TestSwitch(ulong val) { switch (val) { case ulong.MinValue: return 0; case ulong.MaxValue: return 1; default: return 1; } } public static void Main() { System.Console.WriteLine(TestSwitch(0)); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(541847, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541847")] [Fact] public void EmitSwitchOnUnsignedLongTypeBoundary2() { string source = @" public class Test { public static object TestSwitch(ulong val) { switch (val) { case (ulong)0: return (ulong)0; case (ulong)1: return (ulong)1; case (ulong)0x7F: return (ulong)0x7F; case (ulong)0xFE: return (ulong)0xFE; case (ulong)0xFF: return (ulong)0xFF; case (ulong)0x7FFE: return (ulong)0x7FFE; case (ulong)0x7FFF: return (ulong)0x7FFF; case (ulong)0xFFFE: return (ulong)0xFFFE; case (ulong)0xFFFF: return (ulong)0xFFFF; case (ulong)0x7FFFFFFE: return (ulong)0x7FFFFFFE; case (ulong)0x7FFFFFFF: return (ulong)0x7FFFFFFF; case (ulong)0xFFFFFFFE: return (ulong)0xFFFFFFFE; case (ulong)0xFFFFFFFF: return (ulong)0xFFFFFFFF; case (ulong)0x7FFFFFFFFFFFFFFE: return (ulong)0x7FFFFFFFFFFFFFFE; case (ulong)0x7FFFFFFFFFFFFFFF: return (ulong)0x7FFFFFFFFFFFFFFF; case (ulong)0xFFFFFFFFFFFFFFFE: return (ulong)0xFFFFFFFFFFFFFFFE; case (ulong)0xFFFFFFFFFFFFFFFF: return (ulong)0xFFFFFFFFFFFFFFFF; default: return null; } } public static void Main() { bool b1 = true; b1 = b1 && (((ulong)0).Equals(TestSwitch(0))); b1 = b1 && (((ulong)1).Equals(TestSwitch(1))); b1 = b1 && (((ulong)0x7F).Equals(TestSwitch(0x7F))); b1 = b1 && (((ulong)0xFE).Equals(TestSwitch(0xFE))); b1 = b1 && (((ulong)0xFF).Equals(TestSwitch(0xFF))); b1 = b1 && (((ulong)0x7FFE).Equals(TestSwitch(0x7FFE))); b1 = b1 && (((ulong)0x7FFF).Equals(TestSwitch(0x7FFF))); b1 = b1 && (((ulong)0xFFFE).Equals(TestSwitch(0xFFFE))); b1 = b1 && (((ulong)0xFFFF).Equals(TestSwitch(0xFFFF))); b1 = b1 && (((ulong)0x7FFFFFFE).Equals(TestSwitch(0x7FFFFFFE))); b1 = b1 && (((ulong)0x7FFFFFFF).Equals(TestSwitch(0x7FFFFFFF))); b1 = b1 && (((ulong)0xFFFFFFFE).Equals(TestSwitch(0xFFFFFFFE))); b1 = b1 && (((ulong)0xFFFFFFFF).Equals(TestSwitch(0xFFFFFFFF))); b1 = b1 && (((ulong)0x7FFFFFFFFFFFFFFE).Equals(TestSwitch(0x7FFFFFFFFFFFFFFE))); b1 = b1 && (((ulong)0x7FFFFFFFFFFFFFFF).Equals(TestSwitch(0x7FFFFFFFFFFFFFFF))); b1 = b1 && (((ulong)0xFFFFFFFFFFFFFFFE).Equals(TestSwitch(0xFFFFFFFFFFFFFFFE))); b1 = b1 && (((ulong)0xFFFFFFFFFFFFFFFF).Equals(TestSwitch(0xFFFFFFFFFFFFFFFF))); System.Console.Write(b1); } } "; CompileAndVerify(source, expectedOutput: "True"); } [WorkItem(541839, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541839")] [Fact] public void EmitSwitchOnShortTypeBoundary() { string source = @" public class Test { public static object TestSwitch(short val) { switch (val) { case (short)short.MinValue: return (short)short.MinValue; case (short)short.MinValue + 1: return (short)short.MinValue + 1; case (short)sbyte.MinValue: return (short)sbyte.MinValue; case (short)-1: return (short)-1; case (short)0: return (short)0; case (short)1: return (short)1; case (short)0x7F: return (short)0x7F; case (short)0xFE: return (short)0xFE; case (short)0xFF: return (short)0xFF; case (short)0x7FFE: return (short)0x7FFE; case (short)0x7FFF: return (short)0x7FFF; default: return null; } } public static void Main() { System.Console.WriteLine(TestSwitch(1)); } } "; CompileAndVerify(source, expectedOutput: "1"); } [WorkItem(542563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542563")] [Fact] public void IncompleteIndexerDeclWithSyntaxErrors() { string source = @" public class Test { public sealed object this"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.False(emitResult.Success); Assert.NotEmpty(emitResult.Diagnostics); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void VariableDeclInsideSwitchCaptureInLambdaExpr() { string source = @" using System; class C { public static void Main() { switch (10) { default: int i = 10; Func<int> f1 = () => i; break; } } }"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.True(emitResult.Success); } [WorkItem(541639, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541639")] [Fact] public void MultipleVariableDeclInsideSwitchCaptureInLambdaExpr() { string source = @" using System; class C { public static void Main() { int i = 0; switch (i) { case 0: int j = 0; Func<int> f1 = () => i + j; break; default: int k = 0; Func<int> f2 = () => i + k; break; } } }"; var compilation = CreateCompilation(source); EmitResult emitResult; using (var output = new MemoryStream()) { emitResult = compilation.Emit(output, pdbStream: null, xmlDocumentationStream: null, win32Resources: null); } Assert.True(emitResult.Success); } #region "PE and metadata bits" [Fact] public void CheckRuntimeMDVersion() { string source = @" class C { public static void Main() { } }"; var compilation = CSharpCompilation.Create( "v2Fx.exe", new[] { Parse(source) }, new[] { Net20.mscorlib }); //EDMAURER this is built with a 2.0 mscorlib. The runtimeMetadataVersion should be the same as the runtimeMetadataVersion stored in the assembly //that contains System.Object. var metadataReader = ModuleMetadata.CreateFromStream(compilation.EmitToStream()).MetadataReader; Assert.Equal("v2.0.50727", metadataReader.MetadataVersion); } [Fact] public void CheckCorflags() { string source = @" class C { public static void Main() { } }"; PEHeaders peHeaders; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.AnyCpu)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.Equal(CorFlags.ILOnly, peHeaders.CorHeader.Flags); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.Equal(CorFlags.ILOnly | CorFlags.Requires32Bit, peHeaders.CorHeader.Flags); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.Equal(CorFlags.ILOnly, peHeaders.CorHeader.Flags); Assert.True(peHeaders.Requires64Bits()); Assert.True(peHeaders.RequiresAmdInstructionSet()); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.AnyCpu32BitPreferred)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.False(peHeaders.Requires64Bits()); Assert.False(peHeaders.RequiresAmdInstructionSet()); Assert.Equal(CorFlags.ILOnly | CorFlags.Requires32Bit | CorFlags.Prefers32Bit, peHeaders.CorHeader.Flags); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.Arm)); peHeaders = new PEHeaders(compilation.EmitToStream()); Assert.False(peHeaders.Requires64Bits()); Assert.False(peHeaders.RequiresAmdInstructionSet()); Assert.Equal(CorFlags.ILOnly, peHeaders.CorHeader.Flags); } [Fact] public void CheckCOFFAndPEOptionalHeaders32() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithPlatform(Platform.X86)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.False(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsDll); Assert.False(peHeaders.IsExe); Assert.False(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); Assert.Equal(0x10000000u, peHeaders.PEHeader.ImageBase); Assert.Equal(0x200, peHeaders.PEHeader.FileAlignment); Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE //Verify additional items Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfHeapCommit); } [Fact] public void CheckCOFFAndPEOptionalHeaders64() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithPlatform(Platform.X64)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.True(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsDll); Assert.False(peHeaders.IsExe); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); // the default value is the same as the 32 bit default value Assert.Equal(0x0000000180000000u, peHeaders.PEHeader.ImageBase); Assert.Equal(0x00000200, peHeaders.PEHeader.FileAlignment); //doesn't change based on architecture. Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE //Verify additional items Assert.Equal(0x00400000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x4000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); Assert.Equal(0x2000u, peHeaders.PEHeader.SizeOfHeapCommit); Assert.Equal(0x8664, (ushort)peHeaders.CoffHeader.Machine); //AMD64 (K8) //default for non-arm, non-appcontainer outputs. EDMAURER: This is an intentional change from Dev11. //Should we find that it is too disruptive. We will consider rolling back. //It turns out to be too disruptive. Rolling back to 4.0 Assert.Equal(4, peHeaders.PEHeader.MajorSubsystemVersion); Assert.Equal(0, peHeaders.PEHeader.MinorSubsystemVersion); //The following ensure that the runtime startup stub was not emitted. It is not needed on modern operating systems. Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.Size); } [Fact] public void CheckCOFFAndPEOptionalHeadersARM() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll.WithPlatform(Platform.Arm)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.False(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsDll); Assert.False(peHeaders.IsExe); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); // the default value is the same as the 32 bit default value Assert.Equal(0x10000000u, peHeaders.PEHeader.ImageBase); Assert.Equal(0x200, peHeaders.PEHeader.FileAlignment); Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE Assert.Equal(0x01c4, (ushort)peHeaders.CoffHeader.Machine); Assert.Equal(6, peHeaders.PEHeader.MajorSubsystemVersion); //Arm targets only run on 6.2 and above Assert.Equal(2, peHeaders.PEHeader.MinorSubsystemVersion); //The following ensure that the runtime startup stub was not emitted. It is not needed on modern operating systems. Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportAddressTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.ImportTableDirectory.Size); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.RelativeVirtualAddress); Assert.Equal(0, peHeaders.PEHeader.BaseRelocationTableDirectory.Size); } [Fact] public void CheckCOFFAndPEOptionalHeadersAnyCPUExe() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.AnyCpu)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.False(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsExe); Assert.False(peHeaders.IsDll); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); Assert.Equal(0x00400000ul, peHeaders.PEHeader.ImageBase); Assert.Equal(0x00000200, peHeaders.PEHeader.FileAlignment); Assert.True(peHeaders.IsConsoleApplication); //should change if this is a windows app. Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); Assert.Equal(0x1000u, peHeaders.PEHeader.SizeOfHeapCommit); //The following ensure that the runtime startup stub was emitted. It is not needed on modern operating systems. Assert.NotEqual(0, peHeaders.PEHeader.ImportAddressTableDirectory.RelativeVirtualAddress); Assert.NotEqual(0, peHeaders.PEHeader.ImportAddressTableDirectory.Size); Assert.NotEqual(0, peHeaders.PEHeader.ImportTableDirectory.RelativeVirtualAddress); Assert.NotEqual(0, peHeaders.PEHeader.ImportTableDirectory.Size); Assert.NotEqual(0, peHeaders.PEHeader.BaseRelocationTableDirectory.RelativeVirtualAddress); Assert.NotEqual(0, peHeaders.PEHeader.BaseRelocationTableDirectory.Size); } [Fact] public void CheckCOFFAndPEOptionalHeaders64Exe() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.True(peHeaders.Requires64Bits()); Assert.True(peHeaders.IsExe); Assert.False(peHeaders.IsDll); Assert.True(peHeaders.CoffHeader.Characteristics.HasFlag(Characteristics.LargeAddressAware)); //interesting Optional PE header bits //We will use a range beginning with 0x30 to identify the Roslyn compiler family. Assert.Equal(0x30, peHeaders.PEHeader.MajorLinkerVersion); Assert.Equal(0, peHeaders.PEHeader.MinorLinkerVersion); Assert.Equal(0x0000000140000000ul, peHeaders.PEHeader.ImageBase); Assert.Equal(0x200, peHeaders.PEHeader.FileAlignment); //doesn't change based on architecture Assert.True(peHeaders.IsConsoleApplication); //should change if this is a windows app. Assert.Equal(0x8540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE Assert.Equal(0x00400000u, peHeaders.PEHeader.SizeOfStackReserve); Assert.Equal(0x4000u, peHeaders.PEHeader.SizeOfStackCommit); Assert.Equal(0x00100000u, peHeaders.PEHeader.SizeOfHeapReserve); //no sure why we don't bump this up relative to 32bit as well. Assert.Equal(0x2000u, peHeaders.PEHeader.SizeOfHeapCommit); } [Fact] public void CheckDllCharacteristicsHighEntropyVA() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(highEntropyVirtualAddressSpace: true))); //interesting COFF bits Assert.Equal(0x8560u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE | HIGH_ENTROPY_VA (0x20) } [WorkItem(764418, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/764418")] [Fact] public void CheckDllCharacteristicsWinRtApp() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.CreateTestOptions(OutputKind.WindowsRuntimeApplication, OptimizationLevel.Debug)); var peHeaders = new PEHeaders(compilation.EmitToStream()); //interesting COFF bits Assert.Equal(0x9540u, (ushort)peHeaders.PEHeader.DllCharacteristics); //DYNAMIC_BASE | NX_COMPAT | NO_SEH | TERMINAL_SERVER_AWARE | IMAGE_DLLCHARACTERISTICS_APPCONTAINER (0x1000) } [Fact] public void CheckBaseAddress() { string source = @" class C { public static void Main() { } }"; // last four hex digits get zero'ed var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0x0000000010111111))); Assert.Equal(0x10110000ul, peHeaders.PEHeader.ImageBase); // test rounding up of values compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0x8000))); Assert.Equal(0x10000ul, peHeaders.PEHeader.ImageBase); // values less than 0x8000 get default baseaddress compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0x7fff))); Assert.Equal(0x00400000u, peHeaders.PEHeader.ImageBase); // default for 32bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream(options: EmitOptions.Default)); Assert.Equal(0x00400000u, peHeaders.PEHeader.ImageBase); // max for 32bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffff7fff))); Assert.Equal(0xffff0000ul, peHeaders.PEHeader.ImageBase); // max+1 for 32bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X86)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffff8000))); Assert.Equal(0x00400000u, peHeaders.PEHeader.ImageBase); compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream(options: EmitOptions.Default)); Assert.Equal(0x0000000140000000u, peHeaders.PEHeader.ImageBase); // max for 64bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffffffffffff7fff))); Assert.Equal(0xffffffffffff0000ul, peHeaders.PEHeader.ImageBase); // max+1 for 64bit compilation = CreateCompilation(source, options: TestOptions.ReleaseExe.WithPlatform(Platform.X64)); peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(baseAddress: 0xffffffffffff8000))); Assert.Equal(0x0000000140000000u, peHeaders.PEHeader.ImageBase); } [Fact] public void CheckFileAlignment() { string source = @" class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseExe); var peHeaders = new PEHeaders(compilation.EmitToStream(options: new EmitOptions(fileAlignment: 1024))); Assert.Equal(1024, peHeaders.PEHeader.FileAlignment); } #endregion [Fact] public void Bug10273() { string source = @" using System; public struct C1 { public int C; public static int B = 12; public void F(){} public int A; } public delegate void B(); public class A1 { public int C; public static int B = 12; public void F(){} public int A; public int I {get; set;} public void E(){} public int H {get; set;} public int G {get; set;} public event Action L; public void D(){} public event Action K; public event Action J; public partial class O { } public partial class N { } public partial class M { } public partial class N{} public partial class M{} public partial class O{} public void F(int x){} public void E(int x){} public void D(int x){} } namespace F{} public class G {} namespace E{} namespace D{} "; CompileAndVerify(source, sourceSymbolValidator: delegate (ModuleSymbol m) { string[] expectedGlobalMembers = { "C1", "B", "A1", "F", "G", "E", "D" }; var actualGlobalMembers = m.GlobalNamespace.GetMembers().Where(member => !member.IsImplicitlyDeclared).ToArray(); for (int i = 0; i < System.Math.Max(expectedGlobalMembers.Length, actualGlobalMembers.Length); i++) { Assert.Equal(expectedGlobalMembers[i], actualGlobalMembers[i].Name); } string[] expectedAMembers = { "C", "B", "F", "A", "<I>k__BackingField", "I", "get_I", "set_I", "E", "<H>k__BackingField", "H", "get_H", "set_H", "<G>k__BackingField", "G", "get_G", "set_G", "add_L", "remove_L", "L", "D", "add_K", "remove_K", "K", "add_J", "remove_J", "J", "O", "N", "M", "F", "E", "D", ".ctor", ".cctor" }; var actualAMembers = ((SourceModuleSymbol)m).GlobalNamespace.GetTypeMembers("A1").Single().GetMembers().ToArray(); for (int i = 0; i < System.Math.Max(expectedAMembers.Length, actualAMembers.Length); i++) { Assert.Equal(expectedAMembers[i], actualAMembers[i].Name); } string[] expectedBMembers = { ".ctor", "Invoke", "BeginInvoke", "EndInvoke" }; var actualBMembers = ((SourceModuleSymbol)m).GlobalNamespace.GetTypeMembers("B").Single().GetMembers().ToArray(); for (int i = 0; i < System.Math.Max(expectedBMembers.Length, actualBMembers.Length); i++) { Assert.Equal(expectedBMembers[i], actualBMembers[i].Name); } string[] expectedCMembers = {".cctor", "C", "B", "F", "A", ".ctor"}; var actualCMembers = ((SourceModuleSymbol)m).GlobalNamespace.GetTypeMembers("C1").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedCMembers, actualCMembers.Select(s => s.Name)); }, symbolValidator: delegate (ModuleSymbol m) { string[] expectedAMembers = {"C", "B", "A", "F", "get_I", "set_I", "E", "get_H", "set_H", "get_G", "set_G", "add_L", "remove_L", "D", "add_K", "remove_K", "add_J", "remove_J", "F", "E", "D", ".ctor", "I", "H", "G", "L", "K", "J", "O", "N", "M", }; var actualAMembers = m.GlobalNamespace.GetTypeMembers("A1").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedAMembers, actualAMembers.Select(s => s.Name)); string[] expectedBMembers = { ".ctor", "BeginInvoke", "EndInvoke", "Invoke" }; var actualBMembers = m.GlobalNamespace.GetTypeMembers("B").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedBMembers, actualBMembers.Select(s => s.Name)); string[] expectedCMembers = { "C", "B", "A", ".ctor", "F" }; var actualCMembers = m.GlobalNamespace.GetTypeMembers("C1").Single().GetMembers().ToArray(); AssertEx.SetEqual(expectedCMembers, actualCMembers.Select(s => s.Name)); } ); } [WorkItem(543763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543763")] [Fact()] public void OptionalParamTypeAsDecimal() { string source = @" public class Test { public static decimal Goo(decimal d = 0) { return d; } public static void Main() { System.Console.WriteLine(Goo()); } } "; CompileAndVerify(source, expectedOutput: "0"); } [WorkItem(543932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543932")] [Fact] public void BranchCodeGenOnConditionDebug() { string source = @" public class Test { public static void Main() { int a_int = 0; if ((a_int != 0) || (false)) { System.Console.WriteLine(""CheckPoint-1""); } System.Console.WriteLine(""CheckPoint-2""); } }"; var compilation = CreateCompilation(source); CompileAndVerify(source, expectedOutput: "CheckPoint-2"); } [Fact] public void EmitAssemblyWithGivenName() { var name = "a"; var extension = ".dll"; var nameWithExtension = name + extension; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(nameWithExtension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameWithExtension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(name, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(nameWithExtension, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a.netmodule to b.netmodule [Fact] public void EmitModuleWithDifferentName() { var name = "a"; var extension = ".netmodule"; var outputName = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseModule.WithModuleName(name + extension), assemblyName: null); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal("?", assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: outputName + extension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.False(peReader.IsAssembly); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a.dll to b.dll - expected use case [Fact] public void EmitAssemblyWithDifferentName1() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride + extension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a.dll to b - odd, but allowable [Fact] public void EmitAssemblyWithDifferentName2() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a to b.dll - odd, but allowable [Fact] public void EmitAssemblyWithDifferentName3() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride + extension)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } // a to b - odd, but allowable [Fact] public void EmitAssemblyWithDifferentName4() { var name = "a"; var extension = ".dll"; var nameOverride = "b"; var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll, assemblyName: name); compilation.VerifyDiagnostics(); var assembly = compilation.Assembly; Assert.Equal(name, assembly.Name); var module = assembly.Modules.Single(); Assert.Equal(name + extension, module.Name); var stream = new MemoryStream(); Assert.True(compilation.Emit(stream, options: new EmitOptions(outputNameOverride: nameOverride)).Success); using (ModuleMetadata metadata = ModuleMetadata.CreateFromImage(stream.ToImmutable())) { var peReader = metadata.Module.GetMetadataReader(); Assert.True(peReader.IsAssembly); Assert.Equal(nameOverride, peReader.GetString(peReader.GetAssemblyDefinition().Name)); Assert.Equal(module.Name, peReader.GetString(peReader.GetModuleDefinition().Name)); } } [WorkItem(570975, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/570975")] [Fact] public void Bug570975() { var source = @" public sealed class ContentType { public void M(System.Collections.Generic.Dictionary<object, object> p) { foreach (object parameterKey in p.Keys) { } } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseModule, assemblyName: "ContentType"); compilation.VerifyDiagnostics(); using (ModuleMetadata block = ModuleMetadata.CreateFromStream(compilation.EmitToStream())) { var reader = block.MetadataReader; foreach (var typeRef in reader.TypeReferences) { EntityHandle scope = reader.GetTypeReference(typeRef).ResolutionScope; if (scope.Kind == HandleKind.TypeReference) { Assert.InRange(reader.GetRowNumber(scope), 1, reader.GetRowNumber(typeRef) - 1); } } } } [Fact] public void IllegalNameOverride() { var compilation = CreateCompilation("class A { }", options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics(); var result = compilation.Emit(new MemoryStream(), options: new EmitOptions(outputNameOverride: "x\0x")); result.Diagnostics.Verify( // error CS2041: Invalid output name: Name contains invalid characters. Diagnostic(ErrorCode.ERR_InvalidOutputName).WithArguments("Name contains invalid characters.").WithLocation(1, 1)); Assert.False(result.Success); } // Verify via MetadataReader - comp option [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes3() { string source = @" class C { public static void Main() { } }"; // Setting the CompilationOption.AllowUnsafe causes an entry to be inserted into the DeclSecurity table var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - comp option, module case [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes4() { string source = @" class C { public static void Main() { } }"; // Setting the CompilationOption.AllowUnsafe causes an entry to be inserted into the DeclSecurity table var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll.WithOutputKind(OutputKind.NetModule)); compilation.VerifyDiagnostics(); CompileAndVerify(compilation, verify: Verification.Skipped, symbolValidator: module => { //no assembly => no decl security row ValidateDeclSecurity(module); }); } // Verify via MetadataReader - attr in source [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes5() { // Writing the attributes in the source should have the same effect as the compilation option. string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - two attrs in source, same action [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes6() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have the SecurityAction, so they should be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (6,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001" + // argument value (true) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - two attrs in source, different actions [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes7() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have different SecurityActions, so they should not be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information."), // (6,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0012" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u000d" + // length of UTF-8 string (small enough to fit in 1 byte) "UnmanagedCode" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - one attr in source, one synthesized, same action [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes8() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have the SecurityAction, so they should be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestMinimum' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestMinimum, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestMinimum").WithArguments("System.Security.Permissions.SecurityAction.RequestMinimum", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0002" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001" + // argument value (true) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } // Verify via MetadataReader - one attr in source, one synthesized, different actions [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.TestExecutionNeedsDesktopTypes)] public void CheckUnsafeAttributes9() { string source = @" using System.Security; using System.Security.Permissions; [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] [module: UnverifiableCode] class C { public static void Main() { } }"; // The attributes have different SecurityActions, so they should not be merged into a single permission set. var compilation = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); compilation.VerifyDiagnostics( // (5,31): warning CS0618: 'System.Security.Permissions.SecurityAction.RequestOptional' is obsolete: 'Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.' // [assembly: SecurityPermission(SecurityAction.RequestOptional, RemotingConfiguration = true)] Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "SecurityAction.RequestOptional").WithArguments("System.Security.Permissions.SecurityAction.RequestOptional", "Assembly level declarative security is obsolete and is no longer enforced by the CLR by default. See http://go.microsoft.com/fwlink/?LinkID=155570 for more information.")); CompileAndVerify(compilation, verify: Verification.Passes, symbolValidator: module => { ValidateDeclSecurity(module, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestOptional, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u001a" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0015" + // length of UTF-8 string (small enough to fit in 1 byte) "RemotingConfiguration" + // property name "\u0001", // argument value (true) }, new DeclSecurityEntry { ActionFlags = DeclarativeSecurityAction.RequestMinimum, ParentKind = SymbolKind.Assembly, PermissionSet = "." + // always start with a dot "\u0001" + // number of attributes (small enough to fit in 1 byte) "\u0080\u0084" + // length of UTF-8 string (0x80 indicates a 2-byte encoding) "System.Security.Permissions.SecurityPermissionAttribute, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" + // attr type name "\u0015" + // number of bytes in the encoding of the named arguments "\u0001" + // number of named arguments "\u0054" + // property (vs field) "\u0002" + // type bool "\u0010" + // length of UTF-8 string (small enough to fit in 1 byte) "SkipVerification" + // property name "\u0001", // argument value (true) }); }); } [Fact] [WorkItem(545651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545651")] private void TestReferenceToNestedGenericType() { string p1 = @"public class Goo<T> { }"; string p2 = @"using System; public class Test { public class C<T> {} public class J<T> : C<Goo<T>> { } public static void Main() { Console.WriteLine(typeof(J<int>).BaseType.Equals(typeof(C<Goo<int>>)) ? 0 : 1); } }"; var c1 = CreateCompilation(p1, options: TestOptions.ReleaseDll, assemblyName: Guid.NewGuid().ToString()); CompileAndVerify(p2, new[] { MetadataReference.CreateFromStream(c1.EmitToStream()) }, expectedOutput: "0"); } [WorkItem(546450, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546450")] [Fact] public void EmitNetModuleWithReferencedNetModule() { string source1 = @"public class A {}"; string source2 = @"public class B: A {}"; var comp = CreateCompilation(source1, options: TestOptions.ReleaseModule); var metadataRef = ModuleMetadata.CreateFromStream(comp.EmitToStream()).GetReference(); CompileAndVerify(source2, references: new[] { metadataRef }, options: TestOptions.ReleaseModule, verify: Verification.Fails); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] [WorkItem(530879, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530879")] public void TestCompilationEmitUsesDifferentStreamsForBinaryAndPdb() { string p1 = @"public class C1 { }"; var c1 = CreateCompilation(p1); var tmpDir = Temp.CreateDirectory(); var dllPath = Path.Combine(tmpDir.Path, "assemblyname.dll"); var pdbPath = Path.Combine(tmpDir.Path, "assemblyname.pdb"); var result = c1.Emit(dllPath, pdbPath); Assert.True(result.Success, "Compilation failed"); Assert.Empty(result.Diagnostics); Assert.True(File.Exists(dllPath), "DLL does not exist"); Assert.True(File.Exists(pdbPath), "PDB does not exist"); } [Fact, WorkItem(540777, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540777"), WorkItem(546354, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546354")] public void CS0219WRN_UnreferencedVarAssg_ConditionalOperator() { var text = @" class Program { static void Main(string[] args) { bool b; int s = (b = false) ? 5 : 100; // Warning } } "; var comp = CreateCompilation(text, options: TestOptions.ReleaseExe).VerifyDiagnostics( // (7,18): warning CS0665: Assignment in conditional expression is always constant; did you mean to use == instead of = ? // int s = (b = false) ? 5 : 100; // Warning Diagnostic(ErrorCode.WRN_IncorrectBooleanAssg, "b = false"), // (6,14): warning CS0219: The variable 'b' is assigned but its value is never used // bool b; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "b").WithArguments("b")); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_01() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); // Confirm that suppressing the old alink warning 1607 shuts off WRN_ConflictingMachineAssembly var warnings = new System.Collections.Generic.Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); useCompilation = useCompilation.WithOptions(useCompilation.Options.WithSpecificDiagnosticOptions(warnings)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_02() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu)); useCompilation.VerifyEmitDiagnostics(emitOptions, // error CS8010: Agnostic assembly cannot have a processor specific module 'PlatformMismatch.netmodule'. Diagnostic(ErrorCode.ERR_AgnosticToMachineModule).WithArguments("PlatformMismatch.netmodule")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86)); useCompilation.VerifyEmitDiagnostics(emitOptions, // error CS8011: Assembly and module 'PlatformMismatch.netmodule' cannot target different processors. Diagnostic(ErrorCode.ERR_ConflictingMachineModule).WithArguments("PlatformMismatch.netmodule")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu)); // no CS8010 when building a module and adding a module that has a conflict. useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_03() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.X86), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // warning CS8012: Referenced assembly 'PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' targets a different processor. Diagnostic(ErrorCode.WRN_ConflictingMachineAssembly).WithArguments("PlatformMismatch, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null")); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_04() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.X86), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions, // error CS8011: Assembly and module 'PlatformMismatch.netmodule' cannot target different processors. Diagnostic(ErrorCode.ERR_ConflictingMachineModule).WithArguments("PlatformMismatch.netmodule")); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_05() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.AnyCpu), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_06() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.AnyCpu), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_07() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var compRef = new CSharpCompilationReference(refCompilation); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { compRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/30169")] public void PlatformMismatch_08() { var emitOptions = new EmitOptions(runtimeMetadataVersion: "v1234"); string refSource = @" public interface ITestPlatform {} "; var refCompilation = CreateEmptyCompilation(refSource, options: TestOptions.ReleaseModule.WithPlatform(Platform.Itanium), assemblyName: "PlatformMismatch"); refCompilation.VerifyEmitDiagnostics(emitOptions); var imageRef = refCompilation.EmitToImageReference(); string useSource = @" public interface IUsePlatform { ITestPlatform M(); } "; var useCompilation = CreateEmptyCompilation(useSource, new MetadataReference[] { imageRef }, options: TestOptions.ReleaseDll.WithPlatform(Platform.Itanium)); useCompilation.VerifyEmitDiagnostics(emitOptions); } [Fact, WorkItem(769741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/769741")] public void Bug769741() { var comp = CreateEmptyCompilation("", new[] { TestReferences.SymbolsTests.netModule.x64COFF }, options: TestOptions.DebugDll); // modules not supported in ref emit CompileAndVerify(comp, verify: Verification.Fails); Assert.NotSame(comp.Assembly.CorLibrary, comp.Assembly); comp.GetSpecialType(SpecialType.System_Int32); } [Fact] public void FoldMethods() { string source = @" class Viewable { static void Main() { var v = new Viewable(); var x = v.P1; var y = x && v.P2; } bool P1 { get { return true; } } bool P2 { get { return true; } } } "; var compilation = CreateCompilation(source, null, TestOptions.ReleaseDll); var peReader = ModuleMetadata.CreateFromStream(compilation.EmitToStream()).Module.GetMetadataReader(); int P1RVA = 0; int P2RVA = 0; foreach (var handle in peReader.TypeDefinitions) { var typeDef = peReader.GetTypeDefinition(handle); if (peReader.StringComparer.Equals(typeDef.Name, "Viewable")) { foreach (var m in typeDef.GetMethods()) { var method = peReader.GetMethodDefinition(m); if (peReader.StringComparer.Equals(method.Name, "get_P1")) { P1RVA = method.RelativeVirtualAddress; } if (peReader.StringComparer.Equals(method.Name, "get_P2")) { P2RVA = method.RelativeVirtualAddress; } } } } Assert.NotEqual(0, P1RVA); Assert.Equal(P2RVA, P1RVA); } private static bool SequenceMatches(byte[] buffer, int startIndex, byte[] pattern) { for (int i = 0; i < pattern.Length; i++) { if (buffer[startIndex + i] != pattern[i]) { return false; } } return true; } private static int IndexOfPattern(byte[] buffer, int startIndex, byte[] pattern) { // Naive linear search for target within buffer int end = buffer.Length - pattern.Length; for (int i = startIndex; i < end; i++) { if (SequenceMatches(buffer, i, pattern)) { return i; } } return -1; } [Fact, WorkItem(1669, "https://github.com/dotnet/roslyn/issues/1669")] public void FoldMethods2() { // Verifies that IL folding eliminates duplicate copies of small method bodies by // examining the emitted binary. string source = @" class C { ulong M() => 0x8675309ABCDE4225UL; long P => -8758040459200282075L; } "; var compilation = CreateCompilation(source, null, TestOptions.ReleaseDll); using (var stream = compilation.EmitToStream()) { var bytes = new byte[stream.Length]; Assert.Equal(bytes.Length, stream.Read(bytes, 0, bytes.Length)); // The constant should appear exactly once byte[] pattern = new byte[] { 0x25, 0x42, 0xDE, 0xBC, 0x9A, 0x30, 0x75, 0x86 }; int firstMatch = IndexOfPattern(bytes, 0, pattern); Assert.True(firstMatch >= 0, "Couldn't find the expected byte pattern in the output."); int secondMatch = IndexOfPattern(bytes, firstMatch + 1, pattern); Assert.True(secondMatch < 0, "Expected to find just one occurrence of the pattern in the output."); } } [Fact] public void BrokenOutStream() { //These tests ensure that users supplying a broken stream implementation via the emit API //get exceptions enabling them to attribute the failure to their code and to debug. string source = @"class Goo {}"; var compilation = CreateCompilation(source); var output = new BrokenStream(); output.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation.Emit(output); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the Portable Executable file. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(output.ThrownException.ToString()).WithLocation(1, 1)); // Stream.Position is not called: output.BreakHow = BrokenStream.BreakHowType.ThrowOnSetPosition; result = compilation.Emit(output); result.Diagnostics.Verify(); // disposed stream is not writable var outReal = new MemoryStream(); outReal.Dispose(); Assert.Throws<ArgumentException>(() => compilation.Emit(outReal)); } [Fact] public void BrokenPortablePdbStream() { string source = @"class Goo {}"; var compilation = CreateCompilation(source); using (new EnsureEnglishUICulture()) using (var output = new MemoryStream()) { var pdbStream = new BrokenStream(); pdbStream.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation.Emit(output, pdbStream, options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb)); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1) ); } } [ConditionalFact(typeof(WindowsOnly), Reason = "https://github.com/dotnet/roslyn/issues/23760")] public void BrokenPDBStream() { string source = @"class Goo {}"; var compilation = CreateCompilation(source, null, TestOptions.DebugDll); var output = new MemoryStream(); var pdb = new BrokenStream(); pdb.BreakHow = BrokenStream.BreakHowType.ThrowOnSetLength; var result = compilation.Emit(output, pdbStream: pdb); // error CS0041: Unexpected error writing debug information -- 'Exception from HRESULT: 0x806D0004' var err = result.Diagnostics.Single(); Assert.Equal((int)ErrorCode.FTL_DebugEmitFailure, err.Code); Assert.Equal(1, err.Arguments.Count); var ioExceptionMessage = new IOException().Message; Assert.Equal(ioExceptionMessage, (string)err.Arguments[0]); pdb.Dispose(); result = compilation.Emit(output, pdbStream: pdb); // error CS0041: Unexpected error writing debug information -- 'Exception from HRESULT: 0x806D0004' err = result.Diagnostics.Single(); Assert.Equal((int)ErrorCode.FTL_DebugEmitFailure, err.Code); Assert.Equal(1, err.Arguments.Count); Assert.Equal(ioExceptionMessage, (string)err.Arguments[0]); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodulesWithPrivateImplementationDetails() { var s1 = @" public class A { private static char[] contents = { 'H', 'e', 'l', 'l', 'o', ',', ' ' }; public static string M1() { return new string(contents); } }"; var s2 = @" public class B : A { private static char[] contents = { 'w', 'o', 'r', 'l', 'd', '!' }; public static string M2() { return new string(contents); } }"; var s3 = @" public class Program { public static void Main(string[] args) { System.Console.Write(A.M1()); System.Console.WriteLine(B.M2()); } }"; var comp1 = CreateCompilation(s1, options: TestOptions.ReleaseModule); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilation(s2, options: TestOptions.ReleaseModule, references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); var comp3 = CreateCompilation(s3, options: TestOptions.ReleaseExe, references: new[] { ref1, ref2 }); // Before the bug was fixed, the PrivateImplementationDetails classes clashed, resulting in the commented-out error below. comp3.VerifyDiagnostics( ////// error CS0101: The namespace '<global namespace>' already contains a definition for '<PrivateImplementationDetails>' ////Diagnostic(ErrorCode.ERR_DuplicateNameInNS).WithArguments("<PrivateImplementationDetails>", "<global namespace>").WithLocation(1, 1) ); CompileAndVerify(comp3, expectedOutput: "Hello, world!"); } [ConditionalFact(typeof(WindowsDesktopOnly), Reason = ConditionalSkipReason.NetModulesNeedDesktop)] public void MultipleNetmodulesWithAnonymousTypes() { var s1 = @" public class A { internal object o1 = new { hello = 1, world = 2 }; public static string M1() { return ""Hello, ""; } }"; var s2 = @" public class B : A { internal object o2 = new { hello = 1, world = 2 }; public static string M2() { return ""world!""; } }"; var s3 = @" public class Program { public static void Main(string[] args) { System.Console.Write(A.M1()); System.Console.WriteLine(B.M2()); } }"; var comp1 = CreateCompilation(s1, options: TestOptions.ReleaseModule.WithModuleName("A")); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilation(s2, options: TestOptions.ReleaseModule.WithModuleName("B"), references: new[] { ref1 }); comp2.VerifyDiagnostics(); var ref2 = comp2.EmitToImageReference(); var comp3 = CreateCompilation(s3, options: TestOptions.ReleaseExe.WithModuleName("C"), references: new[] { ref1, ref2 }); comp3.VerifyDiagnostics(); CompileAndVerify(comp3, expectedOutput: "Hello, world!"); } /// <summary> /// Ordering of anonymous type definitions /// in metadata should be deterministic. /// </summary> [Fact] public void AnonymousTypeMetadataOrder() { var source = @"class C1 { object F = new { A = 1, B = 2 }; } class C2 { object F = new { a = 3, b = 4 }; } class C3 { object F = new { AB = 3 }; } class C4 { object F = new { a = 1, B = 2 }; } class C5 { object F = new { a = 1, B = 2 }; } class C6 { object F = new { Ab = 5 }; }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); var bytes = compilation.EmitToArray(); using (var metadata = ModuleMetadata.CreateFromImage(bytes)) { var reader = metadata.MetadataReader; var actualNames = reader.GetTypeDefNames().Select(h => reader.GetString(h)); var expectedNames = new[] { "<Module>", "<>f__AnonymousType0`2", "<>f__AnonymousType1`2", "<>f__AnonymousType2`1", "<>f__AnonymousType3`2", "<>f__AnonymousType4`1", "C1", "C2", "C3", "C4", "C5", "C6", }; AssertEx.Equal(expectedNames, actualNames); } } /// <summary> /// Ordering of synthesized delegates in /// metadata should be deterministic. /// </summary> [WorkItem(1440, "https://github.com/dotnet/roslyn/issues/1440")] [Fact] public void SynthesizedDelegateMetadataOrder() { var source = @"class C1 { static void M(dynamic d, object x, int y) { d(1, ref x, out y); } } class C2 { static object M(dynamic d, object o) { return d(o, ref o); } } class C3 { static void M(dynamic d, object o) { d(ref o); } } class C4 { static int M(dynamic d, object o) { return d(ref o, 2); } }"; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll, references: new[] { CSharpRef }); var bytes = compilation.EmitToArray(); using (var metadata = ModuleMetadata.CreateFromImage(bytes)) { var reader = metadata.MetadataReader; var actualNames = reader.GetTypeDefNames().Select(h => reader.GetString(h)); var expectedNames = new[] { "<Module>", "<>A{00000010}`3", "<>A{00000140}`5", "<>F{00000010}`5", "<>F{00000040}`5", "C1", "C2", "C3", "C4", "<>o__0", "<>o__0", "<>o__0", "<>o__0", }; AssertEx.Equal(expectedNames, actualNames); } } [Fact] [WorkItem(3240, "https://github.com/dotnet/roslyn/pull/8227")] public void FailingEmitter() { string source = @" public class X { public static void Main() { } }"; var compilation = CreateCompilation(source); var broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; var result = compilation.Emit(broken); Assert.False(result.Success); result.Diagnostics.Verify( // error CS8104: An error occurred while writing the Portable Executable file. Diagnostic(ErrorCode.ERR_PeWritingFailure).WithArguments(broken.ThrownException.ToString()).WithLocation(1, 1)); } [Fact] public void BadPdbStreamWithPortablePdbEmit() { var comp = CreateCompilation("class C {}"); var broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.ThrowOnWrite; using (new EnsureEnglishUICulture()) using (var peStream = new MemoryStream()) { var portablePdbOptions = EmitOptions.Default .WithDebugInformationFormat(DebugInformationFormat.PortablePdb); var result = comp.Emit(peStream, pdbStream: broken, options: portablePdbOptions); Assert.False(result.Success); result.Diagnostics.Verify( // error CS0041: Unexpected error writing debug information -- 'I/O error occurred.' Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("I/O error occurred.").WithLocation(1, 1)); // Allow for cancellation broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.CancelOnWrite; Assert.Throws<OperationCanceledException>(() => comp.Emit(peStream, pdbStream: broken, options: portablePdbOptions)); } } [Fact] [WorkItem(9308, "https://github.com/dotnet/roslyn/issues/9308")] public void FailingEmitterAllowsCancellationExceptionsThrough() { string source = @" public class X { public static void Main() { } }"; var compilation = CreateCompilation(source); var broken = new BrokenStream(); broken.BreakHow = BrokenStream.BreakHowType.CancelOnWrite; Assert.Throws<OperationCanceledException>(() => compilation.Emit(broken)); } [Fact] [WorkItem(11691, "https://github.com/dotnet/roslyn/issues/11691")] public void ObsoleteAttributeOverride() { string source = @" using System; public abstract class BaseClass<T> { public abstract int Method(T input); } public class DerivingClass<T> : BaseClass<T> { [Obsolete(""Deprecated"")] public override void Method(T input) { throw new NotImplementedException(); } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (11,26): warning CS0809: Obsolete member 'DerivingClass<T>.Method(T)' overrides non-obsolete member 'BaseClass<T>.Method(T)' // public override void Method(T input) Diagnostic(ErrorCode.WRN_ObsoleteOverridingNonObsolete, "Method").WithArguments("DerivingClass<T>.Method(T)", "BaseClass<T>.Method(T)").WithLocation(11, 26), // (11,26): error CS0508: 'DerivingClass<T>.Method(T)': return type must be 'int' to match overridden member 'BaseClass<T>.Method(T)' // public override void Method(T input) Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "Method").WithArguments("DerivingClass<T>.Method(T)", "BaseClass<T>.Method(T)", "int").WithLocation(11, 26)); } [Fact] public void CompileAndVerifyModuleIncludesAllModules() { // Before this change, CompileAndVerify() didn't include other modules when testing a PEModule. // Verify that symbols from other modules are accessible as well. var modRef = CreateCompilation("public class A { }", options: TestOptions.ReleaseModule, assemblyName: "refMod").EmitToImageReference(); var comp = CreateCompilation("public class B : A { }", references: new[] { modRef }, assemblyName: "sourceMod"); CompileAndVerify(comp, symbolValidator: module => { var b = module.GlobalNamespace.GetTypeMember("B"); Assert.Equal("B", b.Name); Assert.False(b.IsErrorType()); Assert.Equal("sourceMod.dll", b.ContainingModule.Name); var a = b.BaseType(); Assert.Equal("A", a.Name); Assert.False(a.IsErrorType()); Assert.Equal("refMod.netmodule", a.ContainingModule.Name); }); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorDoesNotEmit_GeneralDiagnosticOption() { var options = TestOptions.DebugDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); TestWarnAsErrorDoesNotEmitCore(options); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorDoesNotEmit_SpecificDiagnosticOption() { var options = TestOptions.DebugDll.WithSpecificDiagnosticOptions("CS0169", ReportDiagnostic.Error); TestWarnAsErrorDoesNotEmitCore(options); } private void TestWarnAsErrorDoesNotEmitCore(CSharpCompilationOptions options) { string source = @" class X { int _f; }"; var compilation = CreateCompilation(source, options: options); using var output = new MemoryStream(); using var pdbStream = new MemoryStream(); using var xmlDocumentationStream = new MemoryStream(); using var win32ResourcesStream = compilation.CreateDefaultWin32Resources(versionResource: true, noManifest: false, manifestContents: null, iconInIcoFormat: null); var emitResult = compilation.Emit(output, pdbStream, xmlDocumentationStream, win32ResourcesStream); Assert.False(emitResult.Success); Assert.Equal(0, output.Length); Assert.Equal(0, pdbStream.Length); // https://github.com/dotnet/roslyn/issues/37996 tracks revisiting the below behavior. Assert.True(xmlDocumentationStream.Length > 0); emitResult.Diagnostics.Verify( // (4,9): error CS0169: The field 'X._f' is never used // int _f; Diagnostic(ErrorCode.WRN_UnreferencedField, "_f").WithArguments("X._f").WithLocation(4, 9).WithWarningAsError(true)); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorWithMetadataOnlyImageDoesEmit_GeneralDiagnosticOption() { var options = TestOptions.DebugDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); TestWarnAsErrorWithMetadataOnlyImageDoesEmitCore(options); } [Fact] [WorkItem(37779, "https://github.com/dotnet/roslyn/issues/37779")] public void WarnAsErrorWithMetadataOnlyImageDoesEmit_SpecificDiagnosticOptions() { var options = TestOptions.DebugDll.WithSpecificDiagnosticOptions("CS0612", ReportDiagnostic.Error); TestWarnAsErrorWithMetadataOnlyImageDoesEmitCore(options); } private void TestWarnAsErrorWithMetadataOnlyImageDoesEmitCore(CSharpCompilationOptions options) { string source = @" public class X { public void M(Y y) { } } [System.Obsolete] public class Y { } "; var compilation = CreateCompilation(source, options: options); using var output = new MemoryStream(); var emitOptions = new EmitOptions(metadataOnly: true); var emitResult = compilation.Emit(output, options: emitOptions); Assert.True(emitResult.Success); Assert.True(output.Length > 0); emitResult.Diagnostics.Verify( // (4,19): error CS0612: 'Y' is obsolete // public void M(Y y) Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "Y").WithArguments("Y").WithLocation(4, 19).WithWarningAsError(true)); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Workspaces/Core/Portable/Workspace/Host/TemporaryStorage/ISupportDirectMemoryAccess.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// support direct memory access pointer /// </summary> internal interface ISupportDirectMemoryAccess { IntPtr GetPointer(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; namespace Microsoft.CodeAnalysis.Host { /// <summary> /// support direct memory access pointer /// </summary> internal interface ISupportDirectMemoryAccess { IntPtr GetPointer(); } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Dependencies/Collections/Internal/IEnumerableCalls`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. using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Collections.Internal { /// <summary> /// Provides static methods to invoke <see cref="IEnumerable{T}"/> members on value types that explicitly implement /// the member. /// </summary> /// <remarks> /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a /// normal call to an implicitly implemented member. /// </remarks> internal static class IEnumerableCalls<T> { public static IEnumerator<T> GetEnumerator<TEnumerable>(ref TEnumerable enumerable) where TEnumerable : IEnumerable<T> { return enumerable.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 Microsoft.CodeAnalysis.Collections.Internal { /// <summary> /// Provides static methods to invoke <see cref="IEnumerable{T}"/> members on value types that explicitly implement /// the member. /// </summary> /// <remarks> /// Normally, invocation of explicit interface members requires boxing or copying the value type, which is /// especially problematic for operations that mutate the value. Invocation through these helpers behaves like a /// normal call to an implicitly implemented member. /// </remarks> internal static class IEnumerableCalls<T> { public static IEnumerator<T> GetEnumerator<TEnumerable>(ref TEnumerable enumerable) where TEnumerable : IEnumerable<T> { return enumerable.GetEnumerator(); } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./docs/compilers/API Notes/4-15-20.md
## API Review Notes for April 15th, 2020 ### Changes reviewed Starting commit: `c827247a767c0c434dcb77496038b163b9e011da` Ending Commit: `3375a7b209d1f590940af043e9e39f2cbb503845` ### Notes #### Everything but Source Generators: * `Project.RemoveDocuments`: Everything else in this type uses `IEnumerable<T>`, not `ImmutableArray<T>`. If we could start again from day 1 we might make everything that, but given that everything today uses the former, we should do so here. This applies to the overloads on `Solution` as well. * `Solution.RemoveAdditonalDocuments/RemoveAnalyzerConfigDocuments`: We added these to `Solution`, but not to project, even though that also has the invididual `Remove` methods. We should add them to `Project` as well. * `DocumentOptionSet.GetOption`: This API was added as a `new` on the concrete `DocumentOptionSet` to cover a change when we moved the implementation up to `OptionSet` and made the method non-virtual. This is not actually a breaking change, so we should remove this. #### Source Generators: As a general note, changes that we make here are _not_ considered breaking changes post 16.6. However, we did take a broad overview of the API surface and have some notes for @chsienki. * `GeneratorAttribute`: we should consider adding a `LanguageName` attribute to this type. * `InitializationContext`: Rename to something like `SourceGeneratorInitialzationContext` or similar. Current name is ambiguous. * `InitializationContext.RegisterForNotifications`: * Naming is inconsistent with existing `Action` ending for analyzer register methods. * `SyntaxReceiverCreator`: all other `RegisterForXAction` methods in analyzers use an `Action` or `Func`, as appropriate. We should consider doing the same here. * `ISyntaxReceiver`: This may be redundant with existing APIs. * `SourceGeneratorContext`: There is not currently a way to share semantic models and other binding info between source generators. We should design a way for this info to be shared so we can avoid introducing lots of binding from generators.
## API Review Notes for April 15th, 2020 ### Changes reviewed Starting commit: `c827247a767c0c434dcb77496038b163b9e011da` Ending Commit: `3375a7b209d1f590940af043e9e39f2cbb503845` ### Notes #### Everything but Source Generators: * `Project.RemoveDocuments`: Everything else in this type uses `IEnumerable<T>`, not `ImmutableArray<T>`. If we could start again from day 1 we might make everything that, but given that everything today uses the former, we should do so here. This applies to the overloads on `Solution` as well. * `Solution.RemoveAdditonalDocuments/RemoveAnalyzerConfigDocuments`: We added these to `Solution`, but not to project, even though that also has the invididual `Remove` methods. We should add them to `Project` as well. * `DocumentOptionSet.GetOption`: This API was added as a `new` on the concrete `DocumentOptionSet` to cover a change when we moved the implementation up to `OptionSet` and made the method non-virtual. This is not actually a breaking change, so we should remove this. #### Source Generators: As a general note, changes that we make here are _not_ considered breaking changes post 16.6. However, we did take a broad overview of the API surface and have some notes for @chsienki. * `GeneratorAttribute`: we should consider adding a `LanguageName` attribute to this type. * `InitializationContext`: Rename to something like `SourceGeneratorInitialzationContext` or similar. Current name is ambiguous. * `InitializationContext.RegisterForNotifications`: * Naming is inconsistent with existing `Action` ending for analyzer register methods. * `SyntaxReceiverCreator`: all other `RegisterForXAction` methods in analyzers use an `Action` or `Func`, as appropriate. We should consider doing the same here. * `ISyntaxReceiver`: This may be redundant with existing APIs. * `SourceGeneratorContext`: There is not currently a way to share semantic models and other binding info between source generators. We should design a way for this info to be shared so we can avoid introducing lots of binding from generators.
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Features/Core/Portable/ConvertIfToSwitch/AbstractConvertIfToSwitchCodeRefactoringProvider.Analyzer.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 Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertIfToSwitch { using static BinaryOperatorKind; internal abstract partial class AbstractConvertIfToSwitchCodeRefactoringProvider< TIfStatementSyntax, TExpressionSyntax, TIsExpressionSyntax, TPatternSyntax> { // Match the following pattern which can be safely converted to switch statement // // <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, ( return | throw ) // | <if-statement> // // <if-statement> // : if (<section-expr>) { _ } else <if-statement> // | if (<section-expr>) { _ } else { <if-statement-sequence> } // | if (<section-expr>) { _ } else { _ } // | if (<section-expr>) { _ } // // <section-expr> // : <section-expr> || <pattern-expr> // | <pattern-expr> // // <pattern-expr> // : <pattern-expr> && <expr> // C# // | <expr0> is <pattern> // C# // | <expr0> is <type> // C# // | <expr0> == <const-expr> // C#, VB // | <expr0> <comparison-op> <const> // C#, VB // | ( <expr0> >= <const> | <const> <= <expr0> ) // && ( <expr0> <= <const> | <const> >= <expr0> ) // C#, VB // | ( <expr0> <= <const> | <const> >= <expr0> ) // && ( <expr0> >= <const> | <const> <= <expr0> ) // C#, VB // internal abstract class Analyzer { public abstract bool CanConvert(IConditionalOperation operation); public abstract bool HasUnreachableEndPoint(IOperation operation); /// <summary> /// Holds the expression determined to be used as the target expression of the switch /// </summary> /// <remarks> /// Note that this is initially unset until we find a non-constant expression. /// </remarks> private SyntaxNode _switchTargetExpression = null!; private readonly ISyntaxFacts _syntaxFacts; protected Analyzer(ISyntaxFacts syntaxFacts, Feature features) { _syntaxFacts = syntaxFacts; Features = features; } public Feature Features { get; } public bool Supports(Feature feature) => (Features & feature) != 0; public (ImmutableArray<AnalyzedSwitchSection>, SyntaxNode TargetExpression) AnalyzeIfStatementSequence(ReadOnlySpan<IOperation> operations) { using var _ = ArrayBuilder<AnalyzedSwitchSection>.GetInstance(out var sections); if (!ParseIfStatementSequence(operations, sections, out var defaultBodyOpt)) { return default; } if (defaultBodyOpt is object) { sections.Add(new AnalyzedSwitchSection(labels: default, defaultBodyOpt, defaultBodyOpt.Syntax)); } RoslynDebug.Assert(_switchTargetExpression is object); return (sections.ToImmutable(), _switchTargetExpression); } // Tree to parse: // // <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, ( return | throw ) // | <if-statement> // private bool ParseIfStatementSequence(ReadOnlySpan<IOperation> operations, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { if (operations.Length > 1 && operations[0] is IConditionalOperation { WhenFalse: null } op && HasUnreachableEndPoint(op.WhenTrue)) { if (!ParseIfStatement(op, sections, out defaultBodyOpt)) { return false; } if (!ParseIfStatementSequence(operations[1..], sections, out defaultBodyOpt)) { var nextStatement = operations[1]; if (nextStatement is IReturnOperation { ReturnedValue: { } } or IThrowOperation { Exception: { } }) { defaultBodyOpt = nextStatement; } } return true; } if (operations.Length > 0) { return ParseIfStatement(operations[0], sections, out defaultBodyOpt); } defaultBodyOpt = null; return false; } // Tree to parse: // // <if-statement> // : if (<section-expr>) { _ } else <if-statement> // | if (<section-expr>) { _ } else { <if-statement-sequence> } // | if (<section-expr>) { _ } else { _ } // | if (<section-expr>) { _ } // private bool ParseIfStatement(IOperation operation, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { switch (operation) { case IConditionalOperation op when CanConvert(op): var section = ParseSwitchSection(op); if (section is null) { break; } sections.Add(section); if (op.WhenFalse is null) { defaultBodyOpt = null; } else if (!ParseIfStatementOrBlock(op.WhenFalse, sections, out defaultBodyOpt)) { defaultBodyOpt = op.WhenFalse; } return true; } defaultBodyOpt = null; return false; } private bool ParseIfStatementOrBlock(IOperation op, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { return op is IBlockOperation block ? ParseIfStatementSequence(block.Operations.AsSpan(), sections, out defaultBodyOpt) : ParseIfStatement(op, sections, out defaultBodyOpt); } private AnalyzedSwitchSection? ParseSwitchSection(IConditionalOperation operation) { using var _ = ArrayBuilder<AnalyzedSwitchLabel>.GetInstance(out var labels); if (!ParseSwitchLabels(operation.Condition, labels)) { return null; } return new AnalyzedSwitchSection(labels.ToImmutable(), operation.WhenTrue, operation.Syntax); } // Tree to parse: // // <section-expr> // : <section-expr> || <pattern-expr> // | <pattern-expr> // private bool ParseSwitchLabels(IOperation operation, ArrayBuilder<AnalyzedSwitchLabel> labels) { if (operation is IBinaryOperation { OperatorKind: ConditionalOr } op) { if (!ParseSwitchLabels(op.LeftOperand, labels)) { return false; } operation = op.RightOperand; } var label = ParseSwitchLabel(operation); if (label is null) { return false; } labels.Add(label); return true; } private AnalyzedSwitchLabel? ParseSwitchLabel(IOperation operation) { using var _ = ArrayBuilder<TExpressionSyntax>.GetInstance(out var guards); var pattern = ParsePattern(operation, guards); if (pattern is null) return null; return new AnalyzedSwitchLabel(pattern, guards.ToImmutable()); } private enum ConstantResult { /// <summary> /// None of operands were constant. /// </summary> None, /// <summary> /// Signifies that the left operand is the constant. /// </summary> Left, /// <summary> /// Signifies that the right operand is the constant. /// </summary> Right, } private ConstantResult DetermineConstant(IBinaryOperation op) { return (op.LeftOperand, op.RightOperand) switch { var (e, v) when IsConstant(v) && CheckTargetExpression(e) => ConstantResult.Right, var (v, e) when IsConstant(v) && CheckTargetExpression(e) => ConstantResult.Left, _ => ConstantResult.None, }; } // Tree to parse: // // <pattern-expr> // : <pattern-expr> && <expr> // C# // | <expr0> is <pattern> // C# // | <expr0> is <type> // C# // | <expr0> == <const-expr> // C#, VB // | <expr0> <comparison-op> <const> // VB // | ( <expr0> >= <const> | <const> <= <expr0> ) // && ( <expr0> <= <const> | <const> >= <expr0> ) // VB // | ( <expr0> <= <const> | <const> >= <expr0> ) // && ( <expr0> >= <const> | <const> <= <expr0> ) // VB // private AnalyzedPattern? ParsePattern(IOperation operation, ArrayBuilder<TExpressionSyntax> guards) { switch (operation) { case IBinaryOperation { OperatorKind: ConditionalAnd } op when Supports(Feature.RangePattern) && GetRangeBounds(op) is (TExpressionSyntax lower, TExpressionSyntax higher): return new AnalyzedPattern.Range(lower, higher); case IBinaryOperation { OperatorKind: BinaryOperatorKind.Equals } op: return DetermineConstant(op) switch { ConstantResult.Left when op.LeftOperand.Syntax is TExpressionSyntax left => new AnalyzedPattern.Constant(left), ConstantResult.Right when op.RightOperand.Syntax is TExpressionSyntax right => new AnalyzedPattern.Constant(right), _ => null }; case IBinaryOperation { OperatorKind: NotEquals } op when Supports(Feature.InequalityPattern): return ParseRelationalPattern(op); case IBinaryOperation op when Supports(Feature.RelationalPattern) && IsRelationalOperator(op.OperatorKind): return ParseRelationalPattern(op); // Check this below the cases that produce Relational/Ranges. We would prefer to use those if // available before utilizing a CaseGuard. case IBinaryOperation { OperatorKind: ConditionalAnd } op when Supports(Feature.AndPattern | Feature.CaseGuard): { var leftPattern = ParsePattern(op.LeftOperand, guards); if (leftPattern == null) return null; if (Supports(Feature.AndPattern)) { var guardCount = guards.Count; var rightPattern = ParsePattern(op.RightOperand, guards); if (rightPattern != null) return new AnalyzedPattern.And(leftPattern, rightPattern); // Making a pattern out of the RHS didn't work. Reset the guards back to where we started. guards.Count = guardCount; } if (Supports(Feature.CaseGuard) && op.RightOperand.Syntax is TExpressionSyntax node) { guards.Add(node); return leftPattern; } return null; } case IIsTypeOperation op when Supports(Feature.IsTypePattern) && CheckTargetExpression(op.ValueOperand) && op.Syntax is TIsExpressionSyntax node: return new AnalyzedPattern.Type(node); case IIsPatternOperation op when Supports(Feature.SourcePattern) && CheckTargetExpression(op.Value) && op.Pattern.Syntax is TPatternSyntax pattern: return new AnalyzedPattern.Source(pattern); case IParenthesizedOperation op: return ParsePattern(op.Operand, guards); } return null; } private AnalyzedPattern? ParseRelationalPattern(IBinaryOperation op) { return DetermineConstant(op) switch { ConstantResult.Left when op.LeftOperand.Syntax is TExpressionSyntax left => new AnalyzedPattern.Relational(Flip(op.OperatorKind), left), ConstantResult.Right when op.RightOperand.Syntax is TExpressionSyntax right => new AnalyzedPattern.Relational(op.OperatorKind, right), _ => null }; } private enum BoundKind { /// <summary> /// Not a range bound. /// </summary> None, /// <summary> /// Signifies that the lower-bound of a range pattern /// </summary> Lower, /// <summary> /// Signifies that the higher-bound of a range pattern /// </summary> Higher, } private (SyntaxNode Lower, SyntaxNode Higher) GetRangeBounds(IBinaryOperation op) { if (op is not { LeftOperand: IBinaryOperation left, RightOperand: IBinaryOperation right }) { return default; } return (GetRangeBound(left), GetRangeBound(right)) switch { ({ Kind: BoundKind.Lower } low, { Kind: BoundKind.Higher } high) when CheckTargetExpression(low.Expression, high.Expression) => (low.Value.Syntax, high.Value.Syntax), ({ Kind: BoundKind.Higher } high, { Kind: BoundKind.Lower } low) when CheckTargetExpression(low.Expression, high.Expression) => (low.Value.Syntax, high.Value.Syntax), _ => default }; bool CheckTargetExpression(IOperation left, IOperation right) => _syntaxFacts.AreEquivalent(left.Syntax, right.Syntax) && this.CheckTargetExpression(left); } private static (BoundKind Kind, IOperation Expression, IOperation Value) GetRangeBound(IBinaryOperation op) { return op.OperatorKind switch { // 5 <= i LessThanOrEqual when IsConstant(op.LeftOperand) => (BoundKind.Lower, op.RightOperand, op.LeftOperand), // i <= 5 LessThanOrEqual when IsConstant(op.RightOperand) => (BoundKind.Higher, op.LeftOperand, op.RightOperand), // 5 >= i GreaterThanOrEqual when IsConstant(op.LeftOperand) => (BoundKind.Higher, op.RightOperand, op.LeftOperand), // i >= 5 GreaterThanOrEqual when IsConstant(op.RightOperand) => (BoundKind.Lower, op.LeftOperand, op.RightOperand), _ => default }; } /// <summary> /// Changes the direction the operator is pointing /// </summary> private static BinaryOperatorKind Flip(BinaryOperatorKind operatorKind) { return operatorKind switch { LessThan => GreaterThan, LessThanOrEqual => GreaterThanOrEqual, GreaterThanOrEqual => LessThanOrEqual, GreaterThan => LessThan, NotEquals => NotEquals, var v => throw ExceptionUtilities.UnexpectedValue(v) }; } private static bool IsRelationalOperator(BinaryOperatorKind operatorKind) { switch (operatorKind) { case LessThan: case LessThanOrEqual: case GreaterThanOrEqual: case GreaterThan: return true; default: return false; } } private static bool IsConstant(IOperation operation) { // Constants do not propagate to conversions return operation is IConversionOperation op ? IsConstant(op.Operand) : operation.ConstantValue.HasValue; } private bool CheckTargetExpression(IOperation operation) { if (operation is IConversionOperation { IsImplicit: false } op) { // Unwrap explicit casts because switch will emit those anyways operation = op.Operand; } var expression = operation.Syntax; // If we have not figured the switch expression yet, // we will assume that the first expression is the one. if (_switchTargetExpression is null) { _switchTargetExpression = expression; return true; } return _syntaxFacts.AreEquivalent(expression, _switchTargetExpression); } } [Flags] internal enum Feature { None = 0, // VB/C# 9.0 features RelationalPattern = 1, // VB features InequalityPattern = 1 << 1, RangePattern = 1 << 2, // C# 7.0 features SourcePattern = 1 << 3, IsTypePattern = 1 << 4, CaseGuard = 1 << 5, // C# 8.0 features SwitchExpression = 1 << 6, // C# 9.0 features OrPattern = 1 << 7, AndPattern = 1 << 8, TypePattern = 1 << 9, } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.ConvertIfToSwitch { using static BinaryOperatorKind; internal abstract partial class AbstractConvertIfToSwitchCodeRefactoringProvider< TIfStatementSyntax, TExpressionSyntax, TIsExpressionSyntax, TPatternSyntax> { // Match the following pattern which can be safely converted to switch statement // // <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, ( return | throw ) // | <if-statement> // // <if-statement> // : if (<section-expr>) { _ } else <if-statement> // | if (<section-expr>) { _ } else { <if-statement-sequence> } // | if (<section-expr>) { _ } else { _ } // | if (<section-expr>) { _ } // // <section-expr> // : <section-expr> || <pattern-expr> // | <pattern-expr> // // <pattern-expr> // : <pattern-expr> && <expr> // C# // | <expr0> is <pattern> // C# // | <expr0> is <type> // C# // | <expr0> == <const-expr> // C#, VB // | <expr0> <comparison-op> <const> // C#, VB // | ( <expr0> >= <const> | <const> <= <expr0> ) // && ( <expr0> <= <const> | <const> >= <expr0> ) // C#, VB // | ( <expr0> <= <const> | <const> >= <expr0> ) // && ( <expr0> >= <const> | <const> <= <expr0> ) // C#, VB // internal abstract class Analyzer { public abstract bool CanConvert(IConditionalOperation operation); public abstract bool HasUnreachableEndPoint(IOperation operation); /// <summary> /// Holds the expression determined to be used as the target expression of the switch /// </summary> /// <remarks> /// Note that this is initially unset until we find a non-constant expression. /// </remarks> private SyntaxNode _switchTargetExpression = null!; private readonly ISyntaxFacts _syntaxFacts; protected Analyzer(ISyntaxFacts syntaxFacts, Feature features) { _syntaxFacts = syntaxFacts; Features = features; } public Feature Features { get; } public bool Supports(Feature feature) => (Features & feature) != 0; public (ImmutableArray<AnalyzedSwitchSection>, SyntaxNode TargetExpression) AnalyzeIfStatementSequence(ReadOnlySpan<IOperation> operations) { using var _ = ArrayBuilder<AnalyzedSwitchSection>.GetInstance(out var sections); if (!ParseIfStatementSequence(operations, sections, out var defaultBodyOpt)) { return default; } if (defaultBodyOpt is object) { sections.Add(new AnalyzedSwitchSection(labels: default, defaultBodyOpt, defaultBodyOpt.Syntax)); } RoslynDebug.Assert(_switchTargetExpression is object); return (sections.ToImmutable(), _switchTargetExpression); } // Tree to parse: // // <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, <if-statement-sequence> // : if (<section-expr>) { <unreachable-end-point> }, ( return | throw ) // | <if-statement> // private bool ParseIfStatementSequence(ReadOnlySpan<IOperation> operations, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { if (operations.Length > 1 && operations[0] is IConditionalOperation { WhenFalse: null } op && HasUnreachableEndPoint(op.WhenTrue)) { if (!ParseIfStatement(op, sections, out defaultBodyOpt)) { return false; } if (!ParseIfStatementSequence(operations[1..], sections, out defaultBodyOpt)) { var nextStatement = operations[1]; if (nextStatement is IReturnOperation { ReturnedValue: { } } or IThrowOperation { Exception: { } }) { defaultBodyOpt = nextStatement; } } return true; } if (operations.Length > 0) { return ParseIfStatement(operations[0], sections, out defaultBodyOpt); } defaultBodyOpt = null; return false; } // Tree to parse: // // <if-statement> // : if (<section-expr>) { _ } else <if-statement> // | if (<section-expr>) { _ } else { <if-statement-sequence> } // | if (<section-expr>) { _ } else { _ } // | if (<section-expr>) { _ } // private bool ParseIfStatement(IOperation operation, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { switch (operation) { case IConditionalOperation op when CanConvert(op): var section = ParseSwitchSection(op); if (section is null) { break; } sections.Add(section); if (op.WhenFalse is null) { defaultBodyOpt = null; } else if (!ParseIfStatementOrBlock(op.WhenFalse, sections, out defaultBodyOpt)) { defaultBodyOpt = op.WhenFalse; } return true; } defaultBodyOpt = null; return false; } private bool ParseIfStatementOrBlock(IOperation op, ArrayBuilder<AnalyzedSwitchSection> sections, out IOperation? defaultBodyOpt) { return op is IBlockOperation block ? ParseIfStatementSequence(block.Operations.AsSpan(), sections, out defaultBodyOpt) : ParseIfStatement(op, sections, out defaultBodyOpt); } private AnalyzedSwitchSection? ParseSwitchSection(IConditionalOperation operation) { using var _ = ArrayBuilder<AnalyzedSwitchLabel>.GetInstance(out var labels); if (!ParseSwitchLabels(operation.Condition, labels)) { return null; } return new AnalyzedSwitchSection(labels.ToImmutable(), operation.WhenTrue, operation.Syntax); } // Tree to parse: // // <section-expr> // : <section-expr> || <pattern-expr> // | <pattern-expr> // private bool ParseSwitchLabels(IOperation operation, ArrayBuilder<AnalyzedSwitchLabel> labels) { if (operation is IBinaryOperation { OperatorKind: ConditionalOr } op) { if (!ParseSwitchLabels(op.LeftOperand, labels)) { return false; } operation = op.RightOperand; } var label = ParseSwitchLabel(operation); if (label is null) { return false; } labels.Add(label); return true; } private AnalyzedSwitchLabel? ParseSwitchLabel(IOperation operation) { using var _ = ArrayBuilder<TExpressionSyntax>.GetInstance(out var guards); var pattern = ParsePattern(operation, guards); if (pattern is null) return null; return new AnalyzedSwitchLabel(pattern, guards.ToImmutable()); } private enum ConstantResult { /// <summary> /// None of operands were constant. /// </summary> None, /// <summary> /// Signifies that the left operand is the constant. /// </summary> Left, /// <summary> /// Signifies that the right operand is the constant. /// </summary> Right, } private ConstantResult DetermineConstant(IBinaryOperation op) { return (op.LeftOperand, op.RightOperand) switch { var (e, v) when IsConstant(v) && CheckTargetExpression(e) => ConstantResult.Right, var (v, e) when IsConstant(v) && CheckTargetExpression(e) => ConstantResult.Left, _ => ConstantResult.None, }; } // Tree to parse: // // <pattern-expr> // : <pattern-expr> && <expr> // C# // | <expr0> is <pattern> // C# // | <expr0> is <type> // C# // | <expr0> == <const-expr> // C#, VB // | <expr0> <comparison-op> <const> // VB // | ( <expr0> >= <const> | <const> <= <expr0> ) // && ( <expr0> <= <const> | <const> >= <expr0> ) // VB // | ( <expr0> <= <const> | <const> >= <expr0> ) // && ( <expr0> >= <const> | <const> <= <expr0> ) // VB // private AnalyzedPattern? ParsePattern(IOperation operation, ArrayBuilder<TExpressionSyntax> guards) { switch (operation) { case IBinaryOperation { OperatorKind: ConditionalAnd } op when Supports(Feature.RangePattern) && GetRangeBounds(op) is (TExpressionSyntax lower, TExpressionSyntax higher): return new AnalyzedPattern.Range(lower, higher); case IBinaryOperation { OperatorKind: BinaryOperatorKind.Equals } op: return DetermineConstant(op) switch { ConstantResult.Left when op.LeftOperand.Syntax is TExpressionSyntax left => new AnalyzedPattern.Constant(left), ConstantResult.Right when op.RightOperand.Syntax is TExpressionSyntax right => new AnalyzedPattern.Constant(right), _ => null }; case IBinaryOperation { OperatorKind: NotEquals } op when Supports(Feature.InequalityPattern): return ParseRelationalPattern(op); case IBinaryOperation op when Supports(Feature.RelationalPattern) && IsRelationalOperator(op.OperatorKind): return ParseRelationalPattern(op); // Check this below the cases that produce Relational/Ranges. We would prefer to use those if // available before utilizing a CaseGuard. case IBinaryOperation { OperatorKind: ConditionalAnd } op when Supports(Feature.AndPattern | Feature.CaseGuard): { var leftPattern = ParsePattern(op.LeftOperand, guards); if (leftPattern == null) return null; if (Supports(Feature.AndPattern)) { var guardCount = guards.Count; var rightPattern = ParsePattern(op.RightOperand, guards); if (rightPattern != null) return new AnalyzedPattern.And(leftPattern, rightPattern); // Making a pattern out of the RHS didn't work. Reset the guards back to where we started. guards.Count = guardCount; } if (Supports(Feature.CaseGuard) && op.RightOperand.Syntax is TExpressionSyntax node) { guards.Add(node); return leftPattern; } return null; } case IIsTypeOperation op when Supports(Feature.IsTypePattern) && CheckTargetExpression(op.ValueOperand) && op.Syntax is TIsExpressionSyntax node: return new AnalyzedPattern.Type(node); case IIsPatternOperation op when Supports(Feature.SourcePattern) && CheckTargetExpression(op.Value) && op.Pattern.Syntax is TPatternSyntax pattern: return new AnalyzedPattern.Source(pattern); case IParenthesizedOperation op: return ParsePattern(op.Operand, guards); } return null; } private AnalyzedPattern? ParseRelationalPattern(IBinaryOperation op) { return DetermineConstant(op) switch { ConstantResult.Left when op.LeftOperand.Syntax is TExpressionSyntax left => new AnalyzedPattern.Relational(Flip(op.OperatorKind), left), ConstantResult.Right when op.RightOperand.Syntax is TExpressionSyntax right => new AnalyzedPattern.Relational(op.OperatorKind, right), _ => null }; } private enum BoundKind { /// <summary> /// Not a range bound. /// </summary> None, /// <summary> /// Signifies that the lower-bound of a range pattern /// </summary> Lower, /// <summary> /// Signifies that the higher-bound of a range pattern /// </summary> Higher, } private (SyntaxNode Lower, SyntaxNode Higher) GetRangeBounds(IBinaryOperation op) { if (op is not { LeftOperand: IBinaryOperation left, RightOperand: IBinaryOperation right }) { return default; } return (GetRangeBound(left), GetRangeBound(right)) switch { ({ Kind: BoundKind.Lower } low, { Kind: BoundKind.Higher } high) when CheckTargetExpression(low.Expression, high.Expression) => (low.Value.Syntax, high.Value.Syntax), ({ Kind: BoundKind.Higher } high, { Kind: BoundKind.Lower } low) when CheckTargetExpression(low.Expression, high.Expression) => (low.Value.Syntax, high.Value.Syntax), _ => default }; bool CheckTargetExpression(IOperation left, IOperation right) => _syntaxFacts.AreEquivalent(left.Syntax, right.Syntax) && this.CheckTargetExpression(left); } private static (BoundKind Kind, IOperation Expression, IOperation Value) GetRangeBound(IBinaryOperation op) { return op.OperatorKind switch { // 5 <= i LessThanOrEqual when IsConstant(op.LeftOperand) => (BoundKind.Lower, op.RightOperand, op.LeftOperand), // i <= 5 LessThanOrEqual when IsConstant(op.RightOperand) => (BoundKind.Higher, op.LeftOperand, op.RightOperand), // 5 >= i GreaterThanOrEqual when IsConstant(op.LeftOperand) => (BoundKind.Higher, op.RightOperand, op.LeftOperand), // i >= 5 GreaterThanOrEqual when IsConstant(op.RightOperand) => (BoundKind.Lower, op.LeftOperand, op.RightOperand), _ => default }; } /// <summary> /// Changes the direction the operator is pointing /// </summary> private static BinaryOperatorKind Flip(BinaryOperatorKind operatorKind) { return operatorKind switch { LessThan => GreaterThan, LessThanOrEqual => GreaterThanOrEqual, GreaterThanOrEqual => LessThanOrEqual, GreaterThan => LessThan, NotEquals => NotEquals, var v => throw ExceptionUtilities.UnexpectedValue(v) }; } private static bool IsRelationalOperator(BinaryOperatorKind operatorKind) { switch (operatorKind) { case LessThan: case LessThanOrEqual: case GreaterThanOrEqual: case GreaterThan: return true; default: return false; } } private static bool IsConstant(IOperation operation) { // Constants do not propagate to conversions return operation is IConversionOperation op ? IsConstant(op.Operand) : operation.ConstantValue.HasValue; } private bool CheckTargetExpression(IOperation operation) { if (operation is IConversionOperation { IsImplicit: false } op) { // Unwrap explicit casts because switch will emit those anyways operation = op.Operand; } var expression = operation.Syntax; // If we have not figured the switch expression yet, // we will assume that the first expression is the one. if (_switchTargetExpression is null) { _switchTargetExpression = expression; return true; } return _syntaxFacts.AreEquivalent(expression, _switchTargetExpression); } } [Flags] internal enum Feature { None = 0, // VB/C# 9.0 features RelationalPattern = 1, // VB features InequalityPattern = 1 << 1, RangePattern = 1 << 2, // C# 7.0 features SourcePattern = 1 << 3, IsTypePattern = 1 << 4, CaseGuard = 1 << 5, // C# 8.0 features SwitchExpression = 1 << 6, // C# 9.0 features OrPattern = 1 << 7, AndPattern = 1 << 8, TypePattern = 1 << 9, } } }
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Tools/ExternalAccess/OmniSharpTest/Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.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.ExternalAccess.OmniSharp.UnitTests</RootNamespace> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\OmniSharp.CSharp\Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp.csproj" /> <ProjectReference Include="..\OmniSharp\Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.csproj" /> </ItemGroup> </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.ExternalAccess.OmniSharp.UnitTests</RootNamespace> <TargetFramework>net472</TargetFramework> </PropertyGroup> <ItemGroup Label="Project References"> <ProjectReference Include="..\..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Resources\Core\Microsoft.CodeAnalysis.Compiler.Test.Resources.csproj" /> <ProjectReference Include="..\..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj" /> <ProjectReference Include="..\..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\OmniSharp.CSharp\Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.CSharp.csproj" /> <ProjectReference Include="..\OmniSharp\Microsoft.CodeAnalysis.ExternalAccess.OmniSharp.csproj" /> </ItemGroup> </Project>
-1
dotnet/roslyn
56,222
Filter the directive trivia when code generation service try to reuse the syntax
Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
Cosifne
"2021-09-07T20:14:41Z"
"2021-09-27T16:54:56Z"
c3f5bda38933dcb91eeedceb0d4a9dda4a4d49f3
07efa604675d82017aa6fd50b3236ab12ccec6eb
Filter the directive trivia when code generation service try to reuse the syntax. Fix https://github.com/dotnet/roslyn/issues/51531 The root cause for this problem is the the directive trivia is a part of the member's syntax node. When the member pulled up to a class, the code generation service try to find its existing node (which include the leading directive), and add it to the base class.
./src/Scripting/CoreTestUtilities/TestCSharpObjectFormatter.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 Microsoft.CodeAnalysis.CSharp.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests { internal sealed class TestCSharpObjectFormatter : CSharpObjectFormatterImpl { private readonly bool _includeCodePoints; private readonly bool _quoteStringsAndCharacters; private readonly int _maximumLineLength; private readonly CultureInfo _cultureInfo; public TestCSharpObjectFormatter(bool includeCodePoints = false, bool quoteStringsAndCharacters = true, int maximumLineLength = int.MaxValue, CultureInfo cultureInfo = null) { _includeCodePoints = includeCodePoints; _quoteStringsAndCharacters = quoteStringsAndCharacters; _maximumLineLength = maximumLineLength; _cultureInfo = cultureInfo ?? CultureInfo.InvariantCulture; } protected override BuilderOptions GetInternalBuilderOptions(PrintOptions printOptions) => new BuilderOptions( indentation: " ", newLine: Environment.NewLine, ellipsis: printOptions.Ellipsis, maximumLineLength: _maximumLineLength, maximumOutputLength: printOptions.MaximumOutputLength); protected override CommonPrimitiveFormatterOptions GetPrimitiveOptions(PrintOptions printOptions) => new CommonPrimitiveFormatterOptions( numberRadix: printOptions.NumberRadix, includeCodePoints: _includeCodePoints, escapeNonPrintableCharacters: printOptions.EscapeNonPrintableCharacters, quoteStringsAndCharacters: _quoteStringsAndCharacters, cultureInfo: _cultureInfo); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET 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 Microsoft.CodeAnalysis.CSharp.Scripting.Hosting; namespace Microsoft.CodeAnalysis.Scripting.Hosting.UnitTests { internal sealed class TestCSharpObjectFormatter : CSharpObjectFormatterImpl { private readonly bool _includeCodePoints; private readonly bool _quoteStringsAndCharacters; private readonly int _maximumLineLength; private readonly CultureInfo _cultureInfo; public TestCSharpObjectFormatter(bool includeCodePoints = false, bool quoteStringsAndCharacters = true, int maximumLineLength = int.MaxValue, CultureInfo cultureInfo = null) { _includeCodePoints = includeCodePoints; _quoteStringsAndCharacters = quoteStringsAndCharacters; _maximumLineLength = maximumLineLength; _cultureInfo = cultureInfo ?? CultureInfo.InvariantCulture; } protected override BuilderOptions GetInternalBuilderOptions(PrintOptions printOptions) => new BuilderOptions( indentation: " ", newLine: Environment.NewLine, ellipsis: printOptions.Ellipsis, maximumLineLength: _maximumLineLength, maximumOutputLength: printOptions.MaximumOutputLength); protected override CommonPrimitiveFormatterOptions GetPrimitiveOptions(PrintOptions printOptions) => new CommonPrimitiveFormatterOptions( numberRadix: printOptions.NumberRadix, includeCodePoints: _includeCodePoints, escapeNonPrintableCharacters: printOptions.EscapeNonPrintableCharacters, quoteStringsAndCharacters: _quoteStringsAndCharacters, cultureInfo: _cultureInfo); } }
-1
dotnet/roslyn
56,218
Eliminate 75GB allocations during binding in a performance trace
Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
sharwell
"2021-09-07T16:51:03Z"
"2021-09-09T22:25:38Z"
e3e8c6e5196d73d1b7582d40a3c48a22c68e6441
ba2203796b7906d6f53b53bc6fa93f1708e11944
Eliminate 75GB allocations during binding in a performance trace. Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
./src/Compilers/CSharp/Portable/Compilation/CSharpCompilation.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.Binder; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The compilation object is an immutable representation of a single invocation of the /// compiler. Although immutable, a compilation is also on-demand, and will realize and cache /// data as necessary. A compilation can produce a new compilation from existing compilation /// with the application of small deltas. In many cases, it is more efficient than creating a /// new compilation from scratch, as the new compilation can reuse information from the old /// compilation. /// </summary> public sealed partial class CSharpCompilation : Compilation { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // 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. // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! private readonly CSharpCompilationOptions _options; private readonly Lazy<UsingsFromOptionsAndDiagnostics> _usingsFromOptions; private readonly Lazy<ImmutableArray<NamespaceOrTypeAndUsingDirective>> _globalImports; private readonly Lazy<Imports> _previousSubmissionImports; private readonly Lazy<AliasSymbol> _globalNamespaceAlias; // alias symbol used to resolve "global::". private readonly Lazy<ImplicitNamedTypeSymbol?> _scriptClass; // The type of host object model if available. private TypeSymbol? _lazyHostObjectTypeSymbol; /// <summary> /// All imports (using directives and extern aliases) in syntax trees in this compilation. /// NOTE: We need to de-dup since the Imports objects that populate the list may be GC'd /// and re-created. /// Values are the sets of dependencies for corresponding directives. /// </summary> private ConcurrentDictionary<ImportInfo, ImmutableArray<AssemblySymbol>>? _lazyImportInfos; // Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly. // NOTE: Presently, we do not cache the per-tree diagnostics. private ImmutableArray<Diagnostic> _lazyClsComplianceDiagnostics; private ImmutableArray<AssemblySymbol> _lazyClsComplianceDependencies; private Conversions? _conversions; /// <summary> /// A conversions object that ignores nullability. /// </summary> internal Conversions Conversions { get { if (_conversions == null) { Interlocked.CompareExchange(ref _conversions, new BuckStopsHereBinder(this).Conversions, null); } return _conversions; } } /// <summary> /// Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent. /// </summary> private readonly AnonymousTypeManager _anonymousTypeManager; private NamespaceSymbol? _lazyGlobalNamespace; internal readonly BuiltInOperators builtInOperators; /// <summary> /// The <see cref="SourceAssemblySymbol"/> for this compilation. Do not access directly, use Assembly property /// instead. This field is lazily initialized by ReferenceManager, ReferenceManager.CacheLockObject must be locked /// while ReferenceManager "calculates" the value and assigns it, several threads must not perform duplicate /// "calculation" simultaneously. /// </summary> private SourceAssemblySymbol? _lazyAssemblySymbol; /// <summary> /// Holds onto data related to reference binding. /// The manager is shared among multiple compilations that we expect to have the same result of reference binding. /// In most cases this can be determined without performing the binding. If the compilation however contains a circular /// metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results. /// We do so by creating a new reference manager for such compilation. /// </summary> private ReferenceManager _referenceManager; private readonly SyntaxAndDeclarationManager _syntaxAndDeclarations; /// <summary> /// Contains the main method of this assembly, if there is one. /// </summary> private EntryPoint? _lazyEntryPoint; /// <summary> /// Emit nullable attributes for only those members that are visible outside the assembly /// (public, protected, and if any [InternalsVisibleTo] attributes, internal members). /// If false, attributes are emitted for all members regardless of visibility. /// </summary> private ThreeState _lazyEmitNullablePublicOnly; /// <summary> /// The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue. /// </summary> private HashSet<SyntaxTree>? _lazyCompilationUnitCompletedTrees; /// <summary> /// The set of trees for which enough analysis was performed in order to record usage of using directives. /// Once all trees are processed the value is set to null. /// </summary> private ImmutableHashSet<SyntaxTree>? _usageOfUsingsRecordedInTrees = ImmutableHashSet<SyntaxTree>.Empty; /// <summary> /// Nullable analysis data for methods, parameter default values, and attributes. /// The key is a symbol for methods or parameters, and syntax for attributes. /// The data is collected during testing only. /// </summary> internal NullableData? NullableAnalysisData; internal sealed class NullableData { internal readonly int MaxRecursionDepth; internal readonly ConcurrentDictionary<object, NullableWalker.Data> Data; internal NullableData(int maxRecursionDepth = -1) { MaxRecursionDepth = maxRecursionDepth; Data = new ConcurrentDictionary<object, NullableWalker.Data>(); } } internal ImmutableHashSet<SyntaxTree>? UsageOfUsingsRecordedInTrees => Volatile.Read(ref _usageOfUsingsRecordedInTrees); public override string Language { get { return LanguageNames.CSharp; } } public override bool IsCaseSensitive { get { return true; } } /// <summary> /// The options the compilation was created with. /// </summary> public new CSharpCompilationOptions Options { get { return _options; } } internal AnonymousTypeManager AnonymousTypeManager { get { return _anonymousTypeManager; } } internal override CommonAnonymousTypeManager CommonAnonymousTypeManager { get { return AnonymousTypeManager; } } /// <summary> /// True when the compiler is run in "strict" mode, in which it enforces the language specification /// in some cases even at the expense of full compatibility. Such differences typically arise when /// earlier versions of the compiler failed to enforce the full language specification. /// </summary> internal bool FeatureStrictEnabled => Feature("strict") != null; /// <summary> /// True when the "peverify-compat" feature flag is set or the language version is below C# 7.2. /// With this flag we will avoid certain patterns known not be compatible with PEVerify. /// The code may be less efficient and may deviate from spec in corner cases. /// The flag is only to be used if PEVerify pass is extremely important. /// </summary> internal bool IsPeVerifyCompatEnabled => LanguageVersion < LanguageVersion.CSharp7_2 || Feature("peverify-compat") != null; /// <summary> /// Returns true if nullable analysis is enabled in the text span represented by the syntax node. /// </summary> /// <remarks> /// This overload is used for member symbols during binding, or for cases other /// than symbols such as attribute arguments and parameter defaults. /// </remarks> internal bool IsNullableAnalysisEnabledIn(SyntaxNode syntax) { return IsNullableAnalysisEnabledIn((CSharpSyntaxTree)syntax.SyntaxTree, syntax.Span); } /// <summary> /// Returns true if nullable analysis is enabled in the text span. /// </summary> /// <remarks> /// This overload is used for member symbols during binding, or for cases other /// than symbols such as attribute arguments and parameter defaults. /// </remarks> internal bool IsNullableAnalysisEnabledIn(CSharpSyntaxTree tree, TextSpan span) { return GetNullableAnalysisValue() ?? tree.IsNullableAnalysisEnabled(span) ?? (Options.NullableContextOptions & NullableContextOptions.Warnings) != 0; } /// <summary> /// Returns true if nullable analysis is enabled for the method. For constructors, the /// region considered may include other constructors and field and property initializers. /// </summary> /// <remarks> /// This overload is intended for callers that rely on symbols rather than syntax. The overload /// uses the cached value calculated during binding (from potentially several spans) /// from <see cref="IsNullableAnalysisEnabledIn(CSharpSyntaxTree, TextSpan)"/>. /// </remarks> internal bool IsNullableAnalysisEnabledIn(MethodSymbol method) { return GetNullableAnalysisValue() ?? method.IsNullableAnalysisEnabled(); } /// <summary> /// Returns true if nullable analysis is enabled for all methods regardless /// of the actual nullable context. /// If this property returns true but IsNullableAnalysisEnabled returns false, /// any nullable analysis should be enabled but results should be ignored. /// </summary> /// <remarks> /// For DEBUG builds, we treat nullable analysis as enabled for all methods /// unless explicitly disabled, so that analysis is run, even though results may /// be ignored, to increase the chance of catching nullable regressions /// (e.g. https://github.com/dotnet/roslyn/issues/40136). /// </remarks> internal bool IsNullableAnalysisEnabledAlways { get { var value = GetNullableAnalysisValue(); #if DEBUG return value != false; #else return value == true; #endif } } /// <summary> /// Returns Feature("run-nullable-analysis") as a bool? value: /// true for "always"; false for "never"; and null otherwise. /// </summary> private bool? GetNullableAnalysisValue() { return Feature("run-nullable-analysis") switch { "always" => true, "never" => false, _ => null, }; } /// <summary> /// The language version that was used to parse the syntax trees of this compilation. /// </summary> public LanguageVersion LanguageVersion { get; } protected override INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity) { return new ExtendedErrorTypeSymbol( container.EnsureCSharpSymbolOrNull(nameof(container)), name, arity, errorInfo: null).GetPublicSymbol(); } protected override INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name) { return new MissingNamespaceSymbol( container.EnsureCSharpSymbolOrNull(nameof(container)), name).GetPublicSymbol(); } #region Constructors and Factories private static readonly CSharpCompilationOptions s_defaultOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication); private static readonly CSharpCompilationOptions s_defaultSubmissionOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithReferencesSupersedeLowerVersions(true); /// <summary> /// Creates a new compilation from scratch. Methods such as AddSyntaxTrees or AddReferences /// on the returned object will allow to continue building up the Compilation incrementally. /// </summary> /// <param name="assemblyName">Simple assembly name.</param> /// <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param> /// <param name="references">The references for the new compilation.</param> /// <param name="options">The compiler options to use.</param> /// <returns>A new compilation.</returns> public static CSharpCompilation Create( string? assemblyName, IEnumerable<SyntaxTree>? syntaxTrees = null, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null) { return Create( assemblyName, options ?? s_defaultOptions, syntaxTrees, references, previousSubmission: null, returnType: null, hostObjectType: null, isSubmission: false); } /// <summary> /// Creates a new compilation that can be used in scripting. /// </summary> public static CSharpCompilation CreateScriptCompilation( string assemblyName, SyntaxTree? syntaxTree = null, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null, CSharpCompilation? previousScriptCompilation = null, Type? returnType = null, Type? globalsType = null) { CheckSubmissionOptions(options); ValidateScriptCompilationParameters(previousScriptCompilation, returnType, ref globalsType); return Create( assemblyName, options?.WithReferencesSupersedeLowerVersions(true) ?? s_defaultSubmissionOptions, (syntaxTree != null) ? new[] { syntaxTree } : SpecializedCollections.EmptyEnumerable<SyntaxTree>(), references, previousScriptCompilation, returnType, globalsType, isSubmission: true); } private static CSharpCompilation Create( string? assemblyName, CSharpCompilationOptions options, IEnumerable<SyntaxTree>? syntaxTrees, IEnumerable<MetadataReference>? references, CSharpCompilation? previousSubmission, Type? returnType, Type? hostObjectType, bool isSubmission) { RoslynDebug.Assert(options != null); Debug.Assert(!isSubmission || options.ReferencesSupersedeLowerVersions); var validatedReferences = ValidateReferences<CSharpCompilationReference>(references); // We can't reuse the whole Reference Manager entirely (reuseReferenceManager = false) // because the set of references of this submission differs from the previous one. // The submission inherits references of the previous submission, adds the previous submission reference // and may add more references passed explicitly or via #r. // // TODO: Consider reusing some results of the assembly binding to improve perf // since most of the binding work is similar. // https://github.com/dotnet/roslyn/issues/43397 var compilation = new CSharpCompilation( assemblyName, options, validatedReferences, previousSubmission, returnType, hostObjectType, isSubmission, referenceManager: null, reuseReferenceManager: false, syntaxAndDeclarations: new SyntaxAndDeclarationManager( ImmutableArray<SyntaxTree>.Empty, options.ScriptClassName, options.SourceReferenceResolver, CSharp.MessageProvider.Instance, isSubmission, state: null), semanticModelProvider: null); if (syntaxTrees != null) { compilation = compilation.AddSyntaxTrees(syntaxTrees); } Debug.Assert(compilation._lazyAssemblySymbol is null); return compilation; } private CSharpCompilation( string? assemblyName, CSharpCompilationOptions options, ImmutableArray<MetadataReference> references, CSharpCompilation? previousSubmission, Type? submissionReturnType, Type? hostObjectType, bool isSubmission, ReferenceManager? referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations, SemanticModelProvider? semanticModelProvider, AsyncQueue<CompilationEvent>? eventQueue = null) : this(assemblyName, options, references, previousSubmission, submissionReturnType, hostObjectType, isSubmission, referenceManager, reuseReferenceManager, syntaxAndDeclarations, SyntaxTreeCommonFeatures(syntaxAndDeclarations.ExternalSyntaxTrees), semanticModelProvider, eventQueue) { } private CSharpCompilation( string? assemblyName, CSharpCompilationOptions options, ImmutableArray<MetadataReference> references, CSharpCompilation? previousSubmission, Type? submissionReturnType, Type? hostObjectType, bool isSubmission, ReferenceManager? referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations, IReadOnlyDictionary<string, string> features, SemanticModelProvider? semanticModelProvider, AsyncQueue<CompilationEvent>? eventQueue = null) : base(assemblyName, references, features, isSubmission, semanticModelProvider, eventQueue) { WellKnownMemberSignatureComparer = new WellKnownMembersSignatureComparer(this); _options = options; this.builtInOperators = new BuiltInOperators(this); _scriptClass = new Lazy<ImplicitNamedTypeSymbol?>(BindScriptClass); _globalImports = new Lazy<ImmutableArray<NamespaceOrTypeAndUsingDirective>>(BindGlobalImports); _usingsFromOptions = new Lazy<UsingsFromOptionsAndDiagnostics>(BindUsingsFromOptions); _previousSubmissionImports = new Lazy<Imports>(ExpandPreviousSubmissionImports); _globalNamespaceAlias = new Lazy<AliasSymbol>(CreateGlobalNamespaceAlias); _anonymousTypeManager = new AnonymousTypeManager(this); this.LanguageVersion = CommonLanguageVersion(syntaxAndDeclarations.ExternalSyntaxTrees); if (isSubmission) { Debug.Assert(previousSubmission == null || previousSubmission.HostObjectType == hostObjectType); this.ScriptCompilationInfo = new CSharpScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType); } else { Debug.Assert(previousSubmission == null && submissionReturnType == null && hostObjectType == null); } if (reuseReferenceManager) { if (referenceManager is null) { throw new ArgumentNullException(nameof(referenceManager)); } referenceManager.AssertCanReuseForCompilation(this); _referenceManager = referenceManager; } else { _referenceManager = new ReferenceManager( MakeSourceAssemblySimpleName(), this.Options.AssemblyIdentityComparer, observedMetadata: referenceManager?.ObservedMetadata); } _syntaxAndDeclarations = syntaxAndDeclarations; Debug.Assert(_lazyAssemblySymbol is null); if (EventQueue != null) EventQueue.TryEnqueue(new CompilationStartedEvent(this)); } internal override void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics) { Debug.Assert(debugEntryPoint != null); // Debug entry point has to be a method definition from this compilation. var methodSymbol = (debugEntryPoint as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol; if (methodSymbol?.DeclaringCompilation != this || !methodSymbol.IsDefinition) { diagnostics.Add(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None); } } private static LanguageVersion CommonLanguageVersion(ImmutableArray<SyntaxTree> syntaxTrees) { LanguageVersion? result = null; foreach (var tree in syntaxTrees) { var version = ((CSharpParseOptions)tree.Options).LanguageVersion; if (result == null) { result = version; } else if (result != version) { throw new ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, nameof(syntaxTrees)); } } return result ?? LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); } /// <summary> /// Create a duplicate of this compilation with different symbol instances. /// </summary> public new CSharpCompilation Clone() { return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, this.SemanticModelProvider); } private CSharpCompilation Update( ReferenceManager referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations) { return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, referenceManager, reuseReferenceManager, syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Creates a new compilation with the specified name. /// </summary> public new CSharpCompilation WithAssemblyName(string? assemblyName) { // Can't reuse references since the source assembly name changed and the referenced symbols might // have internals-visible-to relationship with this compilation or they might had a circular reference // to this compilation. return new CSharpCompilation( assemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: assemblyName == this.AssemblyName, _syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> /// <remarks> /// The new <see cref="CSharpCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying /// metadata as soon as the are needed. /// /// The new compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>. /// E.g. if the current compilation references a metadata file that has changed since the creation of the compilation /// the new compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change). /// </remarks> public new CSharpCompilation WithReferences(IEnumerable<MetadataReference>? references) { // References might have changed, don't reuse reference manager. // Don't even reuse observed metadata - let the manager query for the metadata again. return new CSharpCompilation( this.AssemblyName, _options, ValidateReferences<CSharpCompilationReference>(references), this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, referenceManager: null, reuseReferenceManager: false, _syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> public new CSharpCompilation WithReferences(params MetadataReference[] references) { return this.WithReferences((IEnumerable<MetadataReference>)references); } /// <summary> /// Creates a new compilation with the specified compilation options. /// </summary> public CSharpCompilation WithOptions(CSharpCompilationOptions options) { var oldOptions = this.Options; bool reuseReferenceManager = oldOptions.CanReuseCompilationReferenceManager(options); bool reuseSyntaxAndDeclarationManager = oldOptions.ScriptClassName == options.ScriptClassName && oldOptions.SourceReferenceResolver == options.SourceReferenceResolver; return new CSharpCompilation( this.AssemblyName, options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager, reuseSyntaxAndDeclarationManager ? _syntaxAndDeclarations : new SyntaxAndDeclarationManager( _syntaxAndDeclarations.ExternalSyntaxTrees, options.ScriptClassName, options.SourceReferenceResolver, _syntaxAndDeclarations.MessageProvider, _syntaxAndDeclarations.IsSubmission, state: null), this.SemanticModelProvider); } /// <summary> /// Returns a new compilation with the given compilation set as the previous submission. /// </summary> public CSharpCompilation WithScriptCompilationInfo(CSharpScriptCompilationInfo? info) { if (info == ScriptCompilationInfo) { return this; } // Metadata references are inherited from the previous submission, // so we can only reuse the manager if we can guarantee that these references are the same. // Check if the previous script compilation doesn't change. // TODO: Consider comparing the metadata references if they have been bound already. // https://github.com/dotnet/roslyn/issues/43397 bool reuseReferenceManager = ReferenceEquals(ScriptCompilationInfo?.PreviousScriptCompilation, info?.PreviousScriptCompilation); return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, info?.PreviousScriptCompilation, info?.ReturnTypeOpt, info?.GlobalsType, isSubmission: info != null, _referenceManager, reuseReferenceManager, _syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Returns a new compilation with the given semantic model provider. /// </summary> internal override Compilation WithSemanticModelProvider(SemanticModelProvider? semanticModelProvider) { if (this.SemanticModelProvider == semanticModelProvider) { return this; } return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, semanticModelProvider); } /// <summary> /// Returns a new compilation with a given event queue. /// </summary> internal override Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue) { return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, this.SemanticModelProvider, eventQueue); } #endregion #region Submission public new CSharpScriptCompilationInfo? ScriptCompilationInfo { get; } internal override ScriptCompilationInfo? CommonScriptCompilationInfo => ScriptCompilationInfo; internal CSharpCompilation? PreviousSubmission => ScriptCompilationInfo?.PreviousScriptCompilation; internal override bool HasSubmissionResult() { Debug.Assert(IsSubmission); // A submission may be empty or comprised of a single script file. var tree = _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault(); if (tree == null) { return false; } var root = tree.GetCompilationUnitRoot(); if (root.HasErrors) { return false; } // Are there any top-level return statements? if (root.DescendantNodes(n => n is GlobalStatementSyntax || n is StatementSyntax || n is CompilationUnitSyntax).Any(n => n.IsKind(SyntaxKind.ReturnStatement))) { return true; } // Is there a trailing expression? var lastGlobalStatement = (GlobalStatementSyntax?)root.Members.LastOrDefault(m => m.IsKind(SyntaxKind.GlobalStatement)); if (lastGlobalStatement != null) { var statement = lastGlobalStatement.Statement; if (statement.IsKind(SyntaxKind.ExpressionStatement)) { var expressionStatement = (ExpressionStatementSyntax)statement; if (expressionStatement.SemicolonToken.IsMissing) { var model = GetSemanticModel(tree); var expression = expressionStatement.Expression; var info = model.GetTypeInfo(expression); return info.ConvertedType?.SpecialType != SpecialType.System_Void; } } } return false; } #endregion #region Syntax Trees (maintain an ordered list) /// <summary> /// The syntax trees (parsed from source code) that this compilation was created with. /// </summary> public new ImmutableArray<SyntaxTree> SyntaxTrees { get { return _syntaxAndDeclarations.GetLazyState().SyntaxTrees; } } /// <summary> /// Returns true if this compilation contains the specified tree. False otherwise. /// </summary> public new bool ContainsSyntaxTree(SyntaxTree? syntaxTree) { return syntaxTree != null && _syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree); } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> public new CSharpCompilation AddSyntaxTrees(params SyntaxTree[] trees) { return AddSyntaxTrees((IEnumerable<SyntaxTree>)trees); } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> public new CSharpCompilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees) { if (trees == null) { throw new ArgumentNullException(nameof(trees)); } if (trees.IsEmpty()) { return this; } // This HashSet is needed so that we don't allow adding the same tree twice // with a single call to AddSyntaxTrees. Rather than using a separate HashSet, // ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we // only allow replacing a single tree at a time. var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance(); var syntaxAndDeclarations = _syntaxAndDeclarations; externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees); bool reuseReferenceManager = true; int i = 0; foreach (var tree in trees.Cast<CSharpSyntaxTree>()) { if (tree == null) { throw new ArgumentNullException($"{nameof(trees)}[{i}]"); } if (!tree.HasCompilationUnitRoot) { throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, $"{nameof(trees)}[{i}]"); } if (externalSyntaxTrees.Contains(tree)) { throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, $"{nameof(trees)}[{i}]"); } if (this.IsSubmission && tree.Options.Kind == SourceCodeKind.Regular) { throw new ArgumentException(CSharpResources.SubmissionCanOnlyInclude, $"{nameof(trees)}[{i}]"); } externalSyntaxTrees.Add(tree); reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives; i++; } externalSyntaxTrees.Free(); if (this.IsSubmission && i > 1) { throw new ArgumentException(CSharpResources.SubmissionCanHaveAtMostOne, nameof(trees)); } syntaxAndDeclarations = syntaxAndDeclarations.AddSyntaxTrees(trees); return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations); } /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> public new CSharpCompilation RemoveSyntaxTrees(params SyntaxTree[] trees) { return RemoveSyntaxTrees((IEnumerable<SyntaxTree>)trees); } /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees) { if (trees == null) { throw new ArgumentNullException(nameof(trees)); } if (trees.IsEmpty()) { return this; } var removeSet = PooledHashSet<SyntaxTree>.GetInstance(); // This HashSet is needed so that we don't allow adding the same tree twice // with a single call to AddSyntaxTrees. Rather than using a separate HashSet, // ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we // only allow replacing a single tree at a time. var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance(); var syntaxAndDeclarations = _syntaxAndDeclarations; externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees); bool reuseReferenceManager = true; int i = 0; foreach (var tree in trees.Cast<CSharpSyntaxTree>()) { if (!externalSyntaxTrees.Contains(tree)) { // Check to make sure this is not a #load'ed tree. var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap; if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(tree, loadedSyntaxTreeMap)) { throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, $"{nameof(trees)}[{i}]"); } throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, $"{nameof(trees)}[{i}]"); } removeSet.Add(tree); reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives; i++; } externalSyntaxTrees.Free(); syntaxAndDeclarations = syntaxAndDeclarations.RemoveSyntaxTrees(removeSet); removeSet.Free(); return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations); } /// <summary> /// Creates a new compilation without any syntax trees. Preserves metadata info /// from this compilation for use with trees added later. /// </summary> public new CSharpCompilation RemoveAllSyntaxTrees() { var syntaxAndDeclarations = _syntaxAndDeclarations; return Update( _referenceManager, reuseReferenceManager: !syntaxAndDeclarations.MayHaveReferenceDirectives(), syntaxAndDeclarations: syntaxAndDeclarations.WithExternalSyntaxTrees(ImmutableArray<SyntaxTree>.Empty)); } /// <summary> /// Creates a new compilation without the old tree but with the new tree. /// </summary> public new CSharpCompilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree? newTree) { // this is just to force a cast exception oldTree = (CSharpSyntaxTree)oldTree; newTree = (CSharpSyntaxTree?)newTree; if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } if (newTree == null) { return this.RemoveSyntaxTrees(oldTree); } else if (newTree == oldTree) { return this; } if (!newTree.HasCompilationUnitRoot) { throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, nameof(newTree)); } var syntaxAndDeclarations = _syntaxAndDeclarations; var externalSyntaxTrees = syntaxAndDeclarations.ExternalSyntaxTrees; if (!externalSyntaxTrees.Contains(oldTree)) { // Check to see if this is a #load'ed tree. var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap; if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(oldTree, loadedSyntaxTreeMap)) { throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, nameof(oldTree)); } throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, nameof(oldTree)); } if (externalSyntaxTrees.Contains(newTree)) { throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, nameof(newTree)); } // TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse. // This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke // that replaces the tree with a new one. // https://github.com/dotnet/roslyn/issues/43397 var reuseReferenceManager = !oldTree.HasReferenceOrLoadDirectives() && !newTree.HasReferenceOrLoadDirectives(); syntaxAndDeclarations = syntaxAndDeclarations.ReplaceSyntaxTree(oldTree, newTree); return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations); } internal override int GetSyntaxTreeOrdinal(SyntaxTree tree) { Debug.Assert(this.ContainsSyntaxTree(tree)); return _syntaxAndDeclarations.GetLazyState().OrdinalMap[tree]; } #endregion #region References internal override CommonReferenceManager CommonGetBoundReferenceManager() { return GetBoundReferenceManager(); } internal new ReferenceManager GetBoundReferenceManager() { if (_lazyAssemblySymbol is null) { _referenceManager.CreateSourceAssemblyForCompilation(this); Debug.Assert(_lazyAssemblySymbol is object); } // referenceManager can only be accessed after we initialized the lazyAssemblySymbol. // In fact, initialization of the assembly symbol might change the reference manager. return _referenceManager; } // for testing only: internal bool ReferenceManagerEquals(CSharpCompilation other) { return ReferenceEquals(_referenceManager, other._referenceManager); } public override ImmutableArray<MetadataReference> DirectiveReferences { get { return GetBoundReferenceManager().DirectiveReferences; } } internal override IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap => GetBoundReferenceManager().ReferenceDirectiveMap; // for testing purposes internal IEnumerable<string> ExternAliases { get { return GetBoundReferenceManager().ExternAliases; } } /// <summary> /// Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation. /// </summary> /// <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or null if there is none.</returns> /// <remarks> /// Uses object identity when comparing two references. /// </remarks> internal new Symbol? GetAssemblyOrModuleSymbol(MetadataReference reference) { if (reference == null) { throw new ArgumentNullException(nameof(reference)); } if (reference.Properties.Kind == MetadataImageKind.Assembly) { return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference); } else { Debug.Assert(reference.Properties.Kind == MetadataImageKind.Module); int index = GetBoundReferenceManager().GetReferencedModuleIndex(reference); return index < 0 ? null : this.Assembly.Modules[index]; } } public override IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get { return Assembly.Modules.SelectMany(module => module.GetReferencedAssemblies()); } } /// <summary> /// All reference directives used in this compilation. /// </summary> internal override IEnumerable<ReferenceDirective> ReferenceDirectives { get { return this.Declarations.ReferenceDirectives; } } /// <summary> /// Returns a metadata reference that a given #r resolves to. /// </summary> /// <param name="directive">#r directive.</param> /// <returns>Metadata reference the specified directive resolves to, or null if the <paramref name="directive"/> doesn't match any #r directive in the compilation.</returns> public MetadataReference? GetDirectiveReference(ReferenceDirectiveTriviaSyntax directive) { RoslynDebug.Assert(directive.SyntaxTree.FilePath is object); MetadataReference? reference; return ReferenceDirectiveMap.TryGetValue((directive.SyntaxTree.FilePath, directive.File.ValueText), out reference) ? reference : null; } /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> public new CSharpCompilation AddReferences(params MetadataReference[] references) { return (CSharpCompilation)base.AddReferences(references); } /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> public new CSharpCompilation AddReferences(IEnumerable<MetadataReference> references) { return (CSharpCompilation)base.AddReferences(references); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> public new CSharpCompilation RemoveReferences(params MetadataReference[] references) { return (CSharpCompilation)base.RemoveReferences(references); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> public new CSharpCompilation RemoveReferences(IEnumerable<MetadataReference> references) { return (CSharpCompilation)base.RemoveReferences(references); } /// <summary> /// Creates a new compilation without any metadata references /// </summary> public new CSharpCompilation RemoveAllReferences() { return (CSharpCompilation)base.RemoveAllReferences(); } /// <summary> /// Creates a new compilation with an old metadata reference replaced with a new metadata reference. /// </summary> public new CSharpCompilation ReplaceReference(MetadataReference oldReference, MetadataReference newReference) { return (CSharpCompilation)base.ReplaceReference(oldReference, newReference); } public override CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default, bool embedInteropTypes = false) { return new CSharpCompilationReference(this, aliases, embedInteropTypes); } /// <summary> /// Get all modules in this compilation, including the source module, added modules, and all /// modules of referenced assemblies that do not come from an assembly with an extern alias. /// Metadata imported from aliased assemblies is not visible at the source level except through /// the use of an extern alias directive. So exclude them from this list which is used to construct /// the global namespace. /// </summary> private void GetAllUnaliasedModules(ArrayBuilder<ModuleSymbol> modules) { // NOTE: This includes referenced modules - they count as modules of the compilation assembly. modules.AddRange(Assembly.Modules); var referenceManager = GetBoundReferenceManager(); for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++) { if (referenceManager.DeclarationsAccessibleWithoutAlias(i)) { modules.AddRange(referenceManager.ReferencedAssemblies[i].Modules); } } } /// <summary> /// Return a list of assembly symbols than can be accessed without using an alias. /// For example: /// 1) /r:A.dll /r:B.dll -> A, B /// 2) /r:Goo=A.dll /r:B.dll -> B /// 3) /r:Goo=A.dll /r:A.dll -> A /// </summary> internal void GetUnaliasedReferencedAssemblies(ArrayBuilder<AssemblySymbol> assemblies) { var referenceManager = GetBoundReferenceManager(); for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++) { if (referenceManager.DeclarationsAccessibleWithoutAlias(i)) { assemblies.Add(referenceManager.ReferencedAssemblies[i]); } } } /// <summary> /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. /// </summary> public new MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol) { return base.GetMetadataReference(assemblySymbol); } private protected override MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol) { if (assemblySymbol is Symbols.PublicModel.AssemblySymbol { UnderlyingAssemblySymbol: var underlyingSymbol }) { return GetMetadataReference(underlyingSymbol); } return null; } internal MetadataReference? GetMetadataReference(AssemblySymbol? assemblySymbol) { return GetBoundReferenceManager().GetMetadataReference(assemblySymbol); } #endregion #region Symbols /// <summary> /// The AssemblySymbol that represents the assembly being created. /// </summary> internal SourceAssemblySymbol SourceAssembly { get { GetBoundReferenceManager(); RoslynDebug.Assert(_lazyAssemblySymbol is object); return _lazyAssemblySymbol; } } /// <summary> /// The AssemblySymbol that represents the assembly being created. /// </summary> internal new AssemblySymbol Assembly { get { return SourceAssembly; } } /// <summary> /// Get a ModuleSymbol that refers to the module being created by compiling all of the code. /// By getting the GlobalNamespace property of that module, all of the namespaces and types /// defined in source code can be obtained. /// </summary> internal new ModuleSymbol SourceModule { get { return Assembly.Modules[0]; } } /// <summary> /// Gets the root namespace that contains all namespaces and types defined in source code or in /// referenced metadata, merged into a single namespace hierarchy. /// </summary> internal new NamespaceSymbol GlobalNamespace { get { if (_lazyGlobalNamespace is null) { // Get the root namespace from each module, and merge them all together // Get all modules in this compilation, ones referenced directly by the compilation // as well as those referenced by all referenced assemblies. var modules = ArrayBuilder<ModuleSymbol>.GetInstance(); GetAllUnaliasedModules(modules); var result = MergedNamespaceSymbol.Create( new NamespaceExtent(this), null, modules.SelectDistinct(m => m.GlobalNamespace)); modules.Free(); Interlocked.CompareExchange(ref _lazyGlobalNamespace, result, null); } return _lazyGlobalNamespace; } } /// <summary> /// Given for the specified module or assembly namespace, gets the corresponding compilation /// namespace (merged namespace representation for all namespace declarations and references /// with contributions for the namespaceSymbol). Can return null if no corresponding /// namespace can be bound in this compilation with the same name. /// </summary> internal new NamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol) { if (namespaceSymbol is Symbols.PublicModel.NamespaceSymbol n && namespaceSymbol.NamespaceKind == NamespaceKind.Compilation && namespaceSymbol.ContainingCompilation == this) { return n.UnderlyingNamespaceSymbol; } var containingNamespace = namespaceSymbol.ContainingNamespace; if (containingNamespace == null) { return this.GlobalNamespace; } var current = GetCompilationNamespace(containingNamespace); if (current is object) { return current.GetNestedNamespace(namespaceSymbol.Name); } return null; } internal NamespaceSymbol? GetCompilationNamespace(NamespaceSymbol namespaceSymbol) { if (namespaceSymbol.NamespaceKind == NamespaceKind.Compilation && namespaceSymbol.ContainingCompilation == this) { return namespaceSymbol; } var containingNamespace = namespaceSymbol.ContainingNamespace; if (containingNamespace == null) { return this.GlobalNamespace; } var current = GetCompilationNamespace(containingNamespace); if (current is object) { return current.GetNestedNamespace(namespaceSymbol.Name); } return null; } private ConcurrentDictionary<string, NamespaceSymbol>? _externAliasTargets; internal bool GetExternAliasTarget(string aliasName, out NamespaceSymbol @namespace) { if (_externAliasTargets == null) { Interlocked.CompareExchange(ref _externAliasTargets, new ConcurrentDictionary<string, NamespaceSymbol>(), null); } else if (_externAliasTargets.TryGetValue(aliasName, out var cached)) { @namespace = cached; return !(@namespace is MissingNamespaceSymbol); } ArrayBuilder<NamespaceSymbol>? builder = null; var referenceManager = GetBoundReferenceManager(); for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++) { if (referenceManager.AliasesOfReferencedAssemblies[i].Contains(aliasName)) { builder = builder ?? ArrayBuilder<NamespaceSymbol>.GetInstance(); builder.Add(referenceManager.ReferencedAssemblies[i].GlobalNamespace); } } bool foundNamespace = builder != null; // We want to cache failures as well as successes so that subsequent incorrect extern aliases with the // same alias will have the same target. @namespace = foundNamespace ? MergedNamespaceSymbol.Create(new NamespaceExtent(this), namespacesToMerge: builder!.ToImmutableAndFree(), containingNamespace: null, nameOpt: null) : new MissingNamespaceSymbol(new MissingModuleSymbol(new MissingAssemblySymbol(new AssemblyIdentity(System.Guid.NewGuid().ToString())), ordinal: -1)); // Use GetOrAdd in case another thread beat us to the punch (i.e. should return the same object for the same alias, every time). @namespace = _externAliasTargets.GetOrAdd(aliasName, @namespace); Debug.Assert(foundNamespace == !(@namespace is MissingNamespaceSymbol)); return foundNamespace; } /// <summary> /// A symbol representing the implicit Script class. This is null if the class is not /// defined in the compilation. /// </summary> internal new NamedTypeSymbol? ScriptClass { get { return _scriptClass.Value; } } /// <summary> /// Resolves a symbol that represents script container (Script class). Uses the /// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol. /// </summary> /// <returns>The Script class symbol or null if it is not defined.</returns> private ImplicitNamedTypeSymbol? BindScriptClass() { return (ImplicitNamedTypeSymbol?)CommonBindScriptClass().GetSymbol(); } internal bool IsSubmissionSyntaxTree(SyntaxTree tree) { Debug.Assert(tree != null); Debug.Assert(!this.IsSubmission || _syntaxAndDeclarations.ExternalSyntaxTrees.Length <= 1); return this.IsSubmission && tree == _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault(); } /// <summary> /// Global imports (including those from previous submissions, if there are any). /// </summary> internal ImmutableArray<NamespaceOrTypeAndUsingDirective> GlobalImports => _globalImports.Value; private ImmutableArray<NamespaceOrTypeAndUsingDirective> BindGlobalImports() { var usingsFromoptions = UsingsFromOptions; var previousSubmission = PreviousSubmission; var previousSubmissionImports = previousSubmission is object ? Imports.ExpandPreviousSubmissionImports(previousSubmission.GlobalImports, this) : ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty; if (usingsFromoptions.UsingNamespacesOrTypes.IsEmpty) { return previousSubmissionImports; } else if (previousSubmissionImports.IsEmpty) { return usingsFromoptions.UsingNamespacesOrTypes; } var boundUsings = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); var uniqueUsings = PooledHashSet<NamespaceOrTypeSymbol>.GetInstance(); boundUsings.AddRange(usingsFromoptions.UsingNamespacesOrTypes); uniqueUsings.AddAll(usingsFromoptions.UsingNamespacesOrTypes.Select(static unt => unt.NamespaceOrType)); foreach (var previousUsing in previousSubmissionImports) { if (uniqueUsings.Add(previousUsing.NamespaceOrType)) { boundUsings.Add(previousUsing); } } uniqueUsings.Free(); return boundUsings.ToImmutableAndFree(); } /// <summary> /// Global imports not including those from previous submissions. /// </summary> private UsingsFromOptionsAndDiagnostics UsingsFromOptions => _usingsFromOptions.Value; private UsingsFromOptionsAndDiagnostics BindUsingsFromOptions() => UsingsFromOptionsAndDiagnostics.FromOptions(this); /// <summary> /// Imports declared by this submission (null if this isn't one). /// </summary> internal Imports GetSubmissionImports() { Debug.Assert(this.IsSubmission); Debug.Assert(_syntaxAndDeclarations.ExternalSyntaxTrees.Length <= 1); // A submission may be empty or comprised of a single script file. var tree = _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault(); if (tree == null) { return Imports.Empty; } return ((SourceNamespaceSymbol)SourceModule.GlobalNamespace).GetImports((CSharpSyntaxNode)tree.GetRoot(), basesBeingResolved: null); } /// <summary> /// Imports from all previous submissions. /// </summary> internal Imports GetPreviousSubmissionImports() => _previousSubmissionImports.Value; private Imports ExpandPreviousSubmissionImports() { Debug.Assert(this.IsSubmission); var previous = this.PreviousSubmission; if (previous == null) { return Imports.Empty; } return Imports.ExpandPreviousSubmissionImports(previous.GetPreviousSubmissionImports(), this).Concat( Imports.ExpandPreviousSubmissionImports(previous.GetSubmissionImports(), this)); } internal AliasSymbol GlobalNamespaceAlias { get { return _globalNamespaceAlias.Value; } } /// <summary> /// Get the symbol for the predefined type from the COR Library referenced by this compilation. /// </summary> internal new NamedTypeSymbol GetSpecialType(SpecialType specialType) { if (specialType <= SpecialType.None || specialType > SpecialType.Count) { throw new ArgumentOutOfRangeException(nameof(specialType), $"Unexpected SpecialType: '{(int)specialType}'."); } NamedTypeSymbol result; if (IsTypeMissing(specialType)) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(specialType.GetMetadataName(), useCLSCompliantNameArityEncoding: true); result = new MissingMetadataTypeSymbol.TopLevel(Assembly.CorLibrary.Modules[0], ref emittedName, specialType); } else { result = Assembly.GetSpecialType(specialType); } Debug.Assert(result.SpecialType == specialType); return result; } /// <summary> /// Get the symbol for the predefined type member from the COR Library referenced by this compilation. /// </summary> internal Symbol GetSpecialTypeMember(SpecialMember specialMember) { return Assembly.GetSpecialTypeMember(specialMember); } internal override ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember) { return GetSpecialTypeMember(specialMember); } internal TypeSymbol GetTypeByReflectionType(Type type, BindingDiagnosticBag diagnostics) { var result = Assembly.GetTypeByReflectionType(type, includeReferences: true); if ((object)result == null) { var errorType = new ExtendedErrorTypeSymbol(this, type.Name, 0, CreateReflectionTypeNotFoundError(type)); diagnostics.Add(errorType.ErrorInfo, NoLocation.Singleton); result = errorType; } return result; } private static CSDiagnosticInfo CreateReflectionTypeNotFoundError(Type type) { // The type or namespace name '{0}' could not be found in the global namespace (are you missing an assembly reference?) return new CSDiagnosticInfo( ErrorCode.ERR_GlobalSingleTypeNameNotFound, new object[] { type.AssemblyQualifiedName ?? "" }, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty ); } protected override ITypeSymbol? CommonScriptGlobalsType => GetHostObjectTypeSymbol()?.GetPublicSymbol(); internal TypeSymbol? GetHostObjectTypeSymbol() { if (HostObjectType != null && _lazyHostObjectTypeSymbol is null) { TypeSymbol symbol = Assembly.GetTypeByReflectionType(HostObjectType, includeReferences: true); if ((object)symbol == null) { MetadataTypeName mdName = MetadataTypeName.FromNamespaceAndTypeName(HostObjectType.Namespace ?? String.Empty, HostObjectType.Name, useCLSCompliantNameArityEncoding: true); symbol = new MissingMetadataTypeSymbol.TopLevel( new MissingAssemblySymbol(AssemblyIdentity.FromAssemblyDefinition(HostObjectType.GetTypeInfo().Assembly)).Modules[0], ref mdName, SpecialType.None, CreateReflectionTypeNotFoundError(HostObjectType)); } Interlocked.CompareExchange(ref _lazyHostObjectTypeSymbol, symbol, null); } return _lazyHostObjectTypeSymbol; } internal SynthesizedInteractiveInitializerMethod? GetSubmissionInitializer() { return (IsSubmission && ScriptClass is object) ? ScriptClass.GetScriptInitializer() : null; } /// <summary> /// Gets the type within the compilation's assembly and all referenced assemblies (other than /// those that can only be referenced via an extern alias) using its canonical CLR metadata name. /// </summary> internal new NamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName) { return this.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: true, isWellKnownType: false, conflicts: out var _); } /// <summary> /// The TypeSymbol for the type 'dynamic' in this Compilation. /// </summary> internal new TypeSymbol DynamicType { get { return AssemblySymbol.DynamicType; } } /// <summary> /// The NamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of /// Error if there was no COR Library in this Compilation. /// </summary> internal new NamedTypeSymbol ObjectType { get { return this.Assembly.ObjectType; } } internal bool DeclaresTheObjectClass { get { return SourceAssembly.DeclaresTheObjectClass; } } internal new MethodSymbol? GetEntryPoint(CancellationToken cancellationToken) { EntryPoint entryPoint = GetEntryPointAndDiagnostics(cancellationToken); return entryPoint.MethodSymbol; } internal EntryPoint GetEntryPointAndDiagnostics(CancellationToken cancellationToken) { if (_lazyEntryPoint == null) { EntryPoint? entryPoint; var simpleProgramEntryPointSymbol = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(this); if (!this.Options.OutputKind.IsApplication() && (this.ScriptClass is null)) { if (simpleProgramEntryPointSymbol is object) { var diagnostics = BindingDiagnosticBag.GetInstance(); diagnostics.Add(ErrorCode.ERR_SimpleProgramNotAnExecutable, simpleProgramEntryPointSymbol.ReturnTypeSyntax.Location); entryPoint = new EntryPoint(null, diagnostics.ToReadOnlyAndFree()); } else { entryPoint = EntryPoint.None; } } else { entryPoint = null; if (this.Options.MainTypeName != null && !this.Options.MainTypeName.IsValidClrTypeName()) { Debug.Assert(!this.Options.Errors.IsDefaultOrEmpty); entryPoint = EntryPoint.None; } if (entryPoint is null) { ImmutableBindingDiagnostic<AssemblySymbol> diagnostics; var entryPointMethod = FindEntryPoint(simpleProgramEntryPointSymbol, cancellationToken, out diagnostics); entryPoint = new EntryPoint(entryPointMethod, diagnostics); } if (this.Options.MainTypeName != null && simpleProgramEntryPointSymbol is object) { var diagnostics = DiagnosticBag.GetInstance(); diagnostics.Add(ErrorCode.ERR_SimpleProgramDisallowsMainType, NoLocation.Singleton); entryPoint = new EntryPoint(entryPoint.MethodSymbol, new ImmutableBindingDiagnostic<AssemblySymbol>( entryPoint.Diagnostics.Diagnostics.Concat(diagnostics.ToReadOnlyAndFree()), entryPoint.Diagnostics.Dependencies)); } } Interlocked.CompareExchange(ref _lazyEntryPoint, entryPoint, null); } return _lazyEntryPoint; } private MethodSymbol? FindEntryPoint(MethodSymbol? simpleProgramEntryPointSymbol, CancellationToken cancellationToken, out ImmutableBindingDiagnostic<AssemblySymbol> sealedDiagnostics) { var diagnostics = BindingDiagnosticBag.GetInstance(); RoslynDebug.Assert(diagnostics.DiagnosticBag is object); var entryPointCandidates = ArrayBuilder<MethodSymbol>.GetInstance(); try { NamedTypeSymbol? mainType; string? mainTypeName = this.Options.MainTypeName; NamespaceSymbol globalNamespace = this.SourceModule.GlobalNamespace; var scriptClass = this.ScriptClass; if (mainTypeName != null) { // Global code is the entry point, ignore all other Mains. if (scriptClass is object) { // CONSIDER: we could use the symbol instead of just the name. diagnostics.Add(ErrorCode.WRN_MainIgnored, NoLocation.Singleton, mainTypeName); return scriptClass.GetScriptEntryPoint(); } var mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split('.')).OfMinimalArity(); if (mainTypeOrNamespace is null) { diagnostics.Add(ErrorCode.ERR_MainClassNotFound, NoLocation.Singleton, mainTypeName); return null; } mainType = mainTypeOrNamespace as NamedTypeSymbol; if (mainType is null || mainType.IsGenericType || (mainType.TypeKind != TypeKind.Class && mainType.TypeKind != TypeKind.Struct && !mainType.IsInterface)) { diagnostics.Add(ErrorCode.ERR_MainClassNotClass, mainTypeOrNamespace.Locations.First(), mainTypeOrNamespace); return null; } AddEntryPointCandidates(entryPointCandidates, mainType.GetMembersUnordered()); } else { mainType = null; AddEntryPointCandidates( entryPointCandidates, this.GetSymbolsWithNameCore(WellKnownMemberNames.EntryPointMethodName, SymbolFilter.Member, cancellationToken)); // Global code is the entry point, ignore all other Mains. if (scriptClass is object || simpleProgramEntryPointSymbol is object) { foreach (var main in entryPointCandidates) { if (main is not SynthesizedSimpleProgramEntryPointSymbol) { diagnostics.Add(ErrorCode.WRN_MainIgnored, main.Locations.First(), main); } } if (scriptClass is object) { return scriptClass.GetScriptEntryPoint(); } RoslynDebug.Assert(simpleProgramEntryPointSymbol is object); entryPointCandidates.Clear(); entryPointCandidates.Add(simpleProgramEntryPointSymbol); } } // Validity and diagnostics are also tracked because they must be conditionally handled // if there are not any "traditional" entrypoints found. var taskEntryPoints = ArrayBuilder<(bool IsValid, MethodSymbol Candidate, BindingDiagnosticBag SpecificDiagnostics)>.GetInstance(); // These diagnostics (warning only) are added to the compilation only if // there were not any main methods found. var noMainFoundDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); RoslynDebug.Assert(noMainFoundDiagnostics.DiagnosticBag is object); bool checkValid(MethodSymbol candidate, bool isCandidate, BindingDiagnosticBag specificDiagnostics) { if (!isCandidate) { noMainFoundDiagnostics.Add(ErrorCode.WRN_InvalidMainSig, candidate.Locations.First(), candidate); noMainFoundDiagnostics.AddRange(specificDiagnostics); return false; } if (candidate.IsGenericMethod || candidate.ContainingType.IsGenericType) { // a single error for partial methods: noMainFoundDiagnostics.Add(ErrorCode.WRN_MainCantBeGeneric, candidate.Locations.First(), candidate); return false; } return true; } var viableEntryPoints = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var candidate in entryPointCandidates) { var perCandidateBag = BindingDiagnosticBag.GetInstance(diagnostics); var (IsCandidate, IsTaskLike) = HasEntryPointSignature(candidate, perCandidateBag); if (IsTaskLike) { taskEntryPoints.Add((IsCandidate, candidate, perCandidateBag)); } else { if (checkValid(candidate, IsCandidate, perCandidateBag)) { if (candidate.IsAsync) { diagnostics.Add(ErrorCode.ERR_NonTaskMainCantBeAsync, candidate.Locations.First(), candidate); } else { diagnostics.AddRange(perCandidateBag); viableEntryPoints.Add(candidate); } } perCandidateBag.Free(); } } if (viableEntryPoints.Count == 0) { foreach (var (IsValid, Candidate, SpecificDiagnostics) in taskEntryPoints) { if (checkValid(Candidate, IsValid, SpecificDiagnostics) && CheckFeatureAvailability(Candidate.ExtractReturnTypeSyntax(), MessageID.IDS_FeatureAsyncMain, diagnostics)) { diagnostics.AddRange(SpecificDiagnostics); viableEntryPoints.Add(Candidate); } } } else if (LanguageVersion >= MessageID.IDS_FeatureAsyncMain.RequiredVersion() && taskEntryPoints.Count > 0) { var taskCandidates = taskEntryPoints.SelectAsArray(s => (Symbol)s.Candidate); var taskLocations = taskCandidates.SelectAsArray(s => s.Locations[0]); foreach (var candidate in taskCandidates) { // Method '{0}' will not be used as an entry point because a synchronous entry point '{1}' was found. var info = new CSDiagnosticInfo( ErrorCode.WRN_SyncAndAsyncEntryPoints, args: new object[] { candidate, viableEntryPoints[0] }, symbols: taskCandidates, additionalLocations: taskLocations); diagnostics.Add(new CSDiagnostic(info, candidate.Locations[0])); } } foreach (var (_, _, SpecificDiagnostics) in taskEntryPoints) { SpecificDiagnostics.Free(); } if (viableEntryPoints.Count == 0) { diagnostics.AddRange(noMainFoundDiagnostics); } else if (mainType is null) { // Filters out diagnostics so that only InvalidMainSig and MainCant'BeGeneric are left. // The reason that Error diagnostics can end up in `noMainFoundDiagnostics` is when // HasEntryPointSignature yields some Error Diagnostics when people implement Task or Task<T> incorrectly. // // We can't add those Errors to the general diagnostics bag because it would break previously-working programs. // The fact that these warnings are not added when csc is invoked with /main is possibly a bug, and is tracked at // https://github.com/dotnet/roslyn/issues/18964 foreach (var diagnostic in noMainFoundDiagnostics.DiagnosticBag.AsEnumerable()) { if (diagnostic.Code == (int)ErrorCode.WRN_InvalidMainSig || diagnostic.Code == (int)ErrorCode.WRN_MainCantBeGeneric) { diagnostics.Add(diagnostic); } } diagnostics.AddDependencies(noMainFoundDiagnostics); } MethodSymbol? entryPoint = null; if (viableEntryPoints.Count == 0) { if (mainType is null) { diagnostics.Add(ErrorCode.ERR_NoEntryPoint, NoLocation.Singleton); } else { diagnostics.Add(ErrorCode.ERR_NoMainInClass, mainType.Locations.First(), mainType); } } else { foreach (var viableEntryPoint in viableEntryPoints) { if (viableEntryPoint.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is { } data) { Debug.Assert(!ReferenceEquals(data, UnmanagedCallersOnlyAttributeData.Uninitialized)); Debug.Assert(!ReferenceEquals(data, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound)); diagnostics.Add(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, viableEntryPoint.Locations.First()); } } if (viableEntryPoints.Count > 1) { viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance); var info = new CSDiagnosticInfo( ErrorCode.ERR_MultipleEntryPoints, args: Array.Empty<object>(), symbols: viableEntryPoints.OfType<Symbol>().AsImmutable(), additionalLocations: viableEntryPoints.Select(m => m.Locations.First()).OfType<Location>().AsImmutable()); diagnostics.Add(new CSDiagnostic(info, viableEntryPoints.First().Locations.First())); } else { entryPoint = viableEntryPoints[0]; } } taskEntryPoints.Free(); viableEntryPoints.Free(); noMainFoundDiagnostics.Free(); return entryPoint; } finally { entryPointCandidates.Free(); sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); } } private static void AddEntryPointCandidates( ArrayBuilder<MethodSymbol> entryPointCandidates, IEnumerable<Symbol> members) { foreach (var member in members) { if (member is MethodSymbol method && method.IsEntryPointCandidate) { entryPointCandidates.Add(method); } } } internal bool ReturnsAwaitableToVoidOrInt(MethodSymbol method, BindingDiagnosticBag diagnostics) { // Common case optimization if (method.ReturnType.IsVoidType() || method.ReturnType.SpecialType == SpecialType.System_Int32) { return false; } if (!(method.ReturnType is NamedTypeSymbol namedType)) { return false; } // Early bail so we only ever check things that are System.Threading.Tasks.Task(<T>) if (!(TypeSymbol.Equals(namedType.ConstructedFrom, GetWellKnownType(WellKnownType.System_Threading_Tasks_Task), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType.ConstructedFrom, GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything2))) { return false; } var syntax = method.ExtractReturnTypeSyntax(); var dumbInstance = new BoundLiteral(syntax, ConstantValue.Null, namedType); var binder = GetBinder(syntax); BoundExpression? result; var success = binder.GetAwaitableExpressionInfo(dumbInstance, out result, syntax, diagnostics); RoslynDebug.Assert(!namedType.IsDynamic()); return success && (result!.Type!.IsVoidType() || result.Type!.SpecialType == SpecialType.System_Int32); } /// <summary> /// Checks if the method has an entry point compatible signature, i.e. /// - the return type is either void, int, or returns a <see cref="System.Threading.Tasks.Task" />, /// or <see cref="System.Threading.Tasks.Task{T}" /> where the return type of GetAwaiter().GetResult() /// is either void or int. /// - has either no parameter or a single parameter of type string[] /// </summary> internal (bool IsCandidate, bool IsTaskLike) HasEntryPointSignature(MethodSymbol method, BindingDiagnosticBag bag) { if (method.IsVararg) { return (false, false); } TypeSymbol returnType = method.ReturnType; bool returnsTaskOrTaskOfInt = false; if (returnType.SpecialType != SpecialType.System_Int32 && !returnType.IsVoidType()) { // Never look for ReturnsAwaitableToVoidOrInt on int32 or void returnsTaskOrTaskOfInt = ReturnsAwaitableToVoidOrInt(method, bag); if (!returnsTaskOrTaskOfInt) { return (false, false); } } if (method.RefKind != RefKind.None) { return (false, returnsTaskOrTaskOfInt); } if (method.Parameters.Length == 0) { return (true, returnsTaskOrTaskOfInt); } if (method.Parameters.Length > 1) { return (false, returnsTaskOrTaskOfInt); } if (!method.ParameterRefKinds.IsDefault) { return (false, returnsTaskOrTaskOfInt); } var firstType = method.Parameters[0].TypeWithAnnotations; if (firstType.TypeKind != TypeKind.Array) { return (false, returnsTaskOrTaskOfInt); } var array = (ArrayTypeSymbol)firstType.Type; return (array.IsSZArray && array.ElementType.SpecialType == SpecialType.System_String, returnsTaskOrTaskOfInt); } internal override bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code) => code == (int)ErrorCode.ERR_NoTypeDef; internal class EntryPoint { public readonly MethodSymbol? MethodSymbol; public readonly ImmutableBindingDiagnostic<AssemblySymbol> Diagnostics; public static readonly EntryPoint None = new EntryPoint(null, ImmutableBindingDiagnostic<AssemblySymbol>.Empty); public EntryPoint(MethodSymbol? methodSymbol, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics) { this.MethodSymbol = methodSymbol; this.Diagnostics = diagnostics; } } internal bool MightContainNoPiaLocalTypes() { return SourceAssembly.MightContainNoPiaLocalTypes(); } // NOTE(cyrusn): There is a bit of a discoverability problem with this method and the same // named method in SyntaxTreeSemanticModel. Technically, i believe these are the appropriate // locations for these methods. This method has no dependencies on anything but the // compilation, while the other method needs a bindings object to determine what bound node // an expression syntax binds to. Perhaps when we document these methods we should explain // where a user can find the other. /// <summary> /// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/>. /// </summary> /// <param name="source">Source type of value to be converted</param> /// <param name="destination">Destination type of value to be converted</param> /// <returns>A <see cref="Conversion"/> that classifies the conversion from the /// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns> public Conversion ClassifyConversion(ITypeSymbol source, ITypeSymbol destination) { // Note that it is possible for there to be both an implicit user-defined conversion // and an explicit built-in conversion from source to destination. In that scenario // this method returns the implicit conversion. if ((object)source == null) { throw new ArgumentNullException(nameof(source)); } if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } TypeSymbol? cssource = source.EnsureCSharpSymbolOrNull(nameof(source)); TypeSymbol? csdest = destination.EnsureCSharpSymbolOrNull(nameof(destination)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return Conversions.ClassifyConversionFromType(cssource, csdest, ref discardedUseSiteInfo); } /// <summary> /// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according /// to this compilation's programming language. /// </summary> /// <param name="source">Source type of value to be converted</param> /// <param name="destination">Destination type of value to be converted</param> /// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the /// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns> public override CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination) { return ClassifyConversion(source, destination).ToCommonConversion(); } internal override IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol? destination, out ConstantValue? constantValue) { constantValue = null; if (destination is null) { return Conversion.NoConversion; } ITypeSymbol? sourceType = source.Type; ConstantValue? sourceConstantValue = source.GetConstantValue(); if (sourceType is null) { if (sourceConstantValue is { IsNull: true } && destination.IsReferenceType) { constantValue = sourceConstantValue; return Conversion.NullLiteral; } return Conversion.NoConversion; } Conversion result = ClassifyConversion(sourceType, destination); if (result.IsReference && sourceConstantValue is { IsNull: true }) { constantValue = sourceConstantValue; } return result; } /// <summary> /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the /// COR Library in this Compilation. /// </summary> internal ArrayTypeSymbol CreateArrayTypeSymbol(TypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.Oblivious) { if ((object)elementType == null) { throw new ArgumentNullException(nameof(elementType)); } if (rank < 1) { throw new ArgumentException(nameof(rank)); } return ArrayTypeSymbol.CreateCSharpArray(this.Assembly, TypeWithAnnotations.Create(elementType, elementNullableAnnotation), rank); } /// <summary> /// Returns a new PointerTypeSymbol representing a pointer type tied to a type in this Compilation. /// </summary> internal PointerTypeSymbol CreatePointerTypeSymbol(TypeSymbol elementType, NullableAnnotation elementNullableAnnotation = NullableAnnotation.Oblivious) { if ((object)elementType == null) { throw new ArgumentNullException(nameof(elementType)); } return new PointerTypeSymbol(TypeWithAnnotations.Create(elementType, elementNullableAnnotation)); } private protected override bool IsSymbolAccessibleWithinCore( ISymbol symbol, ISymbol within, ITypeSymbol? throughType) { Symbol? symbol0 = symbol.EnsureCSharpSymbolOrNull(nameof(symbol)); Symbol? within0 = within.EnsureCSharpSymbolOrNull(nameof(within)); TypeSymbol? throughType0 = throughType.EnsureCSharpSymbolOrNull(nameof(throughType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return within0.Kind == SymbolKind.Assembly ? AccessCheck.IsSymbolAccessible(symbol0, (AssemblySymbol)within0, ref discardedUseSiteInfo) : AccessCheck.IsSymbolAccessible(symbol0, (NamedTypeSymbol)within0, ref discardedUseSiteInfo, throughType0); } [Obsolete("Compilation.IsSymbolAccessibleWithin is not designed for use within the compilers", true)] internal new bool IsSymbolAccessibleWithin( ISymbol symbol, ISymbol within, ITypeSymbol? throughType = null) { throw new NotImplementedException(); } private ConcurrentSet<MethodSymbol>? _moduleInitializerMethods; internal void AddModuleInitializerMethod(MethodSymbol method) { Debug.Assert(!_declarationDiagnosticsFrozen); LazyInitializer.EnsureInitialized(ref _moduleInitializerMethods).Add(method); } #endregion #region Binding /// <summary> /// Gets a new SyntaxTreeSemanticModel for the specified syntax tree. /// </summary> public new SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) { if (syntaxTree == null) { throw new ArgumentNullException(nameof(syntaxTree)); } if (!_syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree)) { throw new ArgumentException(CSharpResources.SyntaxTreeNotFound, nameof(syntaxTree)); } SemanticModel? model = null; if (SemanticModelProvider != null) { model = SemanticModelProvider.GetSemanticModel(syntaxTree, this, ignoreAccessibility); Debug.Assert(model != null); } return model ?? CreateSemanticModel(syntaxTree, ignoreAccessibility); } internal override SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) => new SyntaxTreeSemanticModel(this, syntaxTree, ignoreAccessibility); // When building symbols from the declaration table (lazily), or inside a type, or when // compiling a method body, we may not have a BinderContext in hand for the enclosing // scopes. Therefore, we build them when needed (and cache them) using a ContextBuilder. // Since a ContextBuilder is only a cache, and the identity of the ContextBuilders and // BinderContexts have no semantic meaning, we can reuse them or rebuild them, whichever is // most convenient. We store them using weak references so that GC pressure will cause them // to be recycled. private WeakReference<BinderFactory>[]? _binderFactories; private WeakReference<BinderFactory>[]? _ignoreAccessibilityBinderFactories; internal BinderFactory GetBinderFactory(SyntaxTree syntaxTree, bool ignoreAccessibility = false) { if (ignoreAccessibility && SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(this) is object) { return GetBinderFactory(syntaxTree, ignoreAccessibility: true, ref _ignoreAccessibilityBinderFactories); } return GetBinderFactory(syntaxTree, ignoreAccessibility: false, ref _binderFactories); } private BinderFactory GetBinderFactory(SyntaxTree syntaxTree, bool ignoreAccessibility, ref WeakReference<BinderFactory>[]? cachedBinderFactories) { Debug.Assert(System.Runtime.CompilerServices.Unsafe.AreSame(ref cachedBinderFactories, ref ignoreAccessibility ? ref _ignoreAccessibilityBinderFactories : ref _binderFactories)); var treeNum = GetSyntaxTreeOrdinal(syntaxTree); WeakReference<BinderFactory>[]? binderFactories = cachedBinderFactories; if (binderFactories == null) { binderFactories = new WeakReference<BinderFactory>[this.SyntaxTrees.Length]; binderFactories = Interlocked.CompareExchange(ref cachedBinderFactories, binderFactories, null) ?? binderFactories; } BinderFactory? previousFactory; var previousWeakReference = binderFactories[treeNum]; if (previousWeakReference != null && previousWeakReference.TryGetTarget(out previousFactory)) { return previousFactory; } return AddNewFactory(syntaxTree, ignoreAccessibility, ref binderFactories[treeNum]); } private BinderFactory AddNewFactory(SyntaxTree syntaxTree, bool ignoreAccessibility, [NotNull] ref WeakReference<BinderFactory>? slot) { var newFactory = new BinderFactory(this, syntaxTree, ignoreAccessibility); var newWeakReference = new WeakReference<BinderFactory>(newFactory); while (true) { BinderFactory? previousFactory; WeakReference<BinderFactory>? previousWeakReference = slot; if (previousWeakReference != null && previousWeakReference.TryGetTarget(out previousFactory)) { Debug.Assert(slot is object); return previousFactory; } if (Interlocked.CompareExchange(ref slot!, newWeakReference, previousWeakReference) == previousWeakReference) { return newFactory; } } } internal Binder GetBinder(CSharpSyntaxNode syntax) { return GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax); } private AliasSymbol CreateGlobalNamespaceAlias() { return AliasSymbol.CreateGlobalNamespaceAlias(this.GlobalNamespace); } private void CompleteTree(SyntaxTree tree) { if (_lazyCompilationUnitCompletedTrees == null) Interlocked.CompareExchange(ref _lazyCompilationUnitCompletedTrees, new HashSet<SyntaxTree>(), null); lock (_lazyCompilationUnitCompletedTrees) { if (_lazyCompilationUnitCompletedTrees.Add(tree)) { // signal the end of the compilation unit EventQueue?.TryEnqueue(new CompilationUnitCompletedEvent(this, tree)); if (_lazyCompilationUnitCompletedTrees.Count == this.SyntaxTrees.Length) { // if that was the last tree, signal the end of compilation CompleteCompilationEventQueue_NoLock(); } } } } internal override void ReportUnusedImports(DiagnosticBag diagnostics, CancellationToken cancellationToken) { ReportUnusedImports(filterTree: null, new BindingDiagnosticBag(diagnostics), cancellationToken); } private void ReportUnusedImports(SyntaxTree? filterTree, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { if (_lazyImportInfos != null && (filterTree is null || ReportUnusedImportsInTree(filterTree))) { PooledHashSet<NamespaceSymbol>? externAliasesToCheck = null; if (diagnostics.DependenciesBag is object) { externAliasesToCheck = PooledHashSet<NamespaceSymbol>.GetInstance(); } foreach (var pair in _lazyImportInfos) { cancellationToken.ThrowIfCancellationRequested(); ImportInfo info = pair.Key; SyntaxTree infoTree = info.Tree; if ((filterTree == null || filterTree == infoTree) && ReportUnusedImportsInTree(infoTree)) { TextSpan infoSpan = info.Span; if (!this.IsImportDirectiveUsed(infoTree, infoSpan.Start)) { ErrorCode code = info.Kind == SyntaxKind.ExternAliasDirective ? ErrorCode.HDN_UnusedExternAlias : ErrorCode.HDN_UnusedUsingDirective; diagnostics.Add(code, infoTree.GetLocation(infoSpan)); } else if (diagnostics.DependenciesBag is object) { RoslynDebug.Assert(externAliasesToCheck is object); ImmutableArray<AssemblySymbol> dependencies = pair.Value; if (!dependencies.IsDefaultOrEmpty) { diagnostics.AddDependencies(dependencies); } else if (info.Kind == SyntaxKind.ExternAliasDirective) { // Record targets of used extern aliases var node = info.Tree.GetRoot(cancellationToken).FindToken(info.Span.Start, findInsideTrivia: false). Parent!.FirstAncestorOrSelf<ExternAliasDirectiveSyntax>(); if (node is object && GetExternAliasTarget(node.Identifier.ValueText, out NamespaceSymbol target)) { externAliasesToCheck.Add(target); } } } } } if (externAliasesToCheck is object) { RoslynDebug.Assert(diagnostics.DependenciesBag is object); // We could do this check after we have built the transitive closure // in GetCompleteSetOfUsedAssemblies.completeTheSetOfUsedAssemblies. However, // the level of accuracy is probably not worth the complexity this would add. var bindingDiagnostics = new BindingDiagnosticBag(diagnosticBag: null, PooledHashSet<AssemblySymbol>.GetInstance()); RoslynDebug.Assert(bindingDiagnostics.DependenciesBag is object); foreach (var aliasedNamespace in externAliasesToCheck) { bindingDiagnostics.Clear(); bindingDiagnostics.AddAssembliesUsedByNamespaceReference(aliasedNamespace); // See if any of the references with the alias are registered as used. We can get in a situation when none of them are. // For example, when the alias was used in a doc comment, but nothing was found within it. We would get only a warning // in this case and no assembly marked as used. if (_lazyUsedAssemblyReferences?.IsEmpty == false || diagnostics.DependenciesBag.Count != 0) { foreach (var assembly in bindingDiagnostics.DependenciesBag) { if (_lazyUsedAssemblyReferences?.Contains(assembly) == true || diagnostics.DependenciesBag.Contains(assembly)) { bindingDiagnostics.DependenciesBag.Clear(); break; } } } diagnostics.AddDependencies(bindingDiagnostics); } bindingDiagnostics.Free(); externAliasesToCheck.Free(); } } CompleteTrees(filterTree); } internal override void CompleteTrees(SyntaxTree? filterTree) { // By definition, a tree is complete when all of its compiler diagnostics have been reported. // Since unused imports are the last thing we compute and report, a tree is complete when // the unused imports have been reported. if (EventQueue != null) { if (filterTree != null) { CompleteTree(filterTree); } else { foreach (var tree in this.SyntaxTrees) { CompleteTree(tree); } } } if (filterTree is null) { _usageOfUsingsRecordedInTrees = null; } } internal void RecordImport(UsingDirectiveSyntax syntax) { RecordImportInternal(syntax); } internal void RecordImport(ExternAliasDirectiveSyntax syntax) { RecordImportInternal(syntax); } private void RecordImportInternal(CSharpSyntaxNode syntax) { // Note: the suppression will be unnecessary once LazyInitializer is properly annotated LazyInitializer.EnsureInitialized(ref _lazyImportInfos)!. TryAdd(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), syntax.Span), default); } internal void RecordImportDependencies(UsingDirectiveSyntax syntax, ImmutableArray<AssemblySymbol> dependencies) { RoslynDebug.Assert(_lazyImportInfos is object); _lazyImportInfos.TryUpdate(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), syntax.Span), dependencies, default); } private struct ImportInfo : IEquatable<ImportInfo> { public readonly SyntaxTree Tree; public readonly SyntaxKind Kind; public readonly TextSpan Span; public ImportInfo(SyntaxTree tree, SyntaxKind kind, TextSpan span) { this.Tree = tree; this.Kind = kind; this.Span = span; } public override bool Equals(object? obj) { return (obj is ImportInfo) && Equals((ImportInfo)obj); } public bool Equals(ImportInfo other) { return other.Kind == this.Kind && other.Tree == this.Tree && other.Span == this.Span; } public override int GetHashCode() { return Hash.Combine(Tree, Span.Start); } } #endregion #region Diagnostics internal override CommonMessageProvider MessageProvider { get { return _syntaxAndDeclarations.MessageProvider; } } /// <summary> /// The bag in which semantic analysis should deposit its diagnostics. /// </summary> internal DiagnosticBag DeclarationDiagnostics { get { // We should only be placing diagnostics in this bag until // we are done gathering declaration diagnostics. Assert that is // the case. But since we have bugs (see https://github.com/dotnet/roslyn/issues/846) // we disable the assertion until they are fixed. Debug.Assert(!_declarationDiagnosticsFrozen || true); if (_lazyDeclarationDiagnostics == null) { var diagnostics = new DiagnosticBag(); Interlocked.CompareExchange(ref _lazyDeclarationDiagnostics, diagnostics, null); } return _lazyDeclarationDiagnostics; } } private DiagnosticBag? _lazyDeclarationDiagnostics; private bool _declarationDiagnosticsFrozen; /// <summary> /// A bag in which diagnostics that should be reported after code gen can be deposited. /// </summary> internal DiagnosticBag AdditionalCodegenWarnings { get { return _additionalCodegenWarnings; } } private readonly DiagnosticBag _additionalCodegenWarnings = new DiagnosticBag(); internal DeclarationTable Declarations { get { return _syntaxAndDeclarations.GetLazyState().DeclarationTable; } } internal MergedNamespaceDeclaration MergedRootDeclaration { get { return Declarations.GetMergedRoot(this); } } /// <summary> /// Gets the diagnostics produced during the parsing stage of a compilation. There are no diagnostics for declarations or accessor or /// method bodies, for example. /// </summary> public override ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(CompilationStage.Parse, false, cancellationToken); } /// <summary> /// Gets the diagnostics produced during symbol declaration headers. There are no diagnostics for accessor or /// method bodies, for example. /// </summary> public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(CompilationStage.Declare, false, cancellationToken); } /// <summary> /// Gets the diagnostics produced during the analysis of method bodies and field initializers. /// </summary> public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(CompilationStage.Compile, false, cancellationToken); } /// <summary> /// Gets the all the diagnostics for the compilation, including syntax, declaration, and binding. Does not /// include any diagnostics that might be produced during emit. /// </summary> public override ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(DefaultDiagnosticsStage, true, cancellationToken); } internal ImmutableArray<Diagnostic> GetDiagnostics(CompilationStage stage, bool includeEarlierStages, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); GetDiagnostics(stage, includeEarlierStages, diagnostics, cancellationToken); return diagnostics.ToReadOnlyAndFree(); } internal override void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default) { DiagnosticBag? builder = DiagnosticBag.GetInstance(); GetDiagnosticsWithoutFiltering(stage, includeEarlierStages, new BindingDiagnosticBag(builder), cancellationToken); // Before returning diagnostics, we filter warnings // to honor the compiler options (e.g., /nowarn, /warnaserror and /warn) and the pragmas. FilterAndAppendAndFreeDiagnostics(diagnostics, ref builder, cancellationToken); } private void GetDiagnosticsWithoutFiltering(CompilationStage stage, bool includeEarlierStages, BindingDiagnosticBag builder, CancellationToken cancellationToken) { RoslynDebug.Assert(builder.DiagnosticBag is object); if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages)) { var syntaxTrees = this.SyntaxTrees; if (this.Options.ConcurrentBuild) { RoslynParallel.For( 0, syntaxTrees.Length, UICultureUtilities.WithCurrentUICulture<int>(i => { var syntaxTree = syntaxTrees[i]; AppendLoadDirectiveDiagnostics(builder.DiagnosticBag, _syntaxAndDeclarations, syntaxTree); builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken)); }), cancellationToken); } else { foreach (var syntaxTree in syntaxTrees) { cancellationToken.ThrowIfCancellationRequested(); AppendLoadDirectiveDiagnostics(builder.DiagnosticBag, _syntaxAndDeclarations, syntaxTree); cancellationToken.ThrowIfCancellationRequested(); builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken)); } } var parseOptionsReported = new HashSet<ParseOptions>(); foreach (var syntaxTree in syntaxTrees) { cancellationToken.ThrowIfCancellationRequested(); if (!syntaxTree.Options.Errors.IsDefaultOrEmpty && parseOptionsReported.Add(syntaxTree.Options)) { var location = syntaxTree.GetLocation(TextSpan.FromBounds(0, 0)); foreach (var error in syntaxTree.Options.Errors) { builder.Add(error.WithLocation(location)); } } } } if (stage == CompilationStage.Declare || stage > CompilationStage.Declare && includeEarlierStages) { CheckAssemblyName(builder.DiagnosticBag); builder.AddRange(Options.Errors); if (Options.NullableContextOptions != NullableContextOptions.Disable && LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion() && _syntaxAndDeclarations.ExternalSyntaxTrees.Any()) { builder.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NullableOptionNotAvailable, nameof(Options.NullableContextOptions), Options.NullableContextOptions, LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion())), Location.None)); } cancellationToken.ThrowIfCancellationRequested(); // the set of diagnostics related to establishing references. builder.AddRange(GetBoundReferenceManager().Diagnostics); cancellationToken.ThrowIfCancellationRequested(); builder.AddRange(GetSourceDeclarationDiagnostics(cancellationToken: cancellationToken), allowMismatchInDependencyAccumulation: true); if (EventQueue != null && SyntaxTrees.Length == 0) { EnsureCompilationEventQueueCompleted(); } } cancellationToken.ThrowIfCancellationRequested(); if (stage == CompilationStage.Compile || stage > CompilationStage.Compile && includeEarlierStages) { var methodBodyDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), builder.DependenciesBag is object ? new ConcurrentSet<AssemblySymbol>() : null); RoslynDebug.Assert(methodBodyDiagnostics.DiagnosticBag is object); GetDiagnosticsForAllMethodBodies(methodBodyDiagnostics, doLowering: false, cancellationToken); builder.AddRange(methodBodyDiagnostics); methodBodyDiagnostics.DiagnosticBag.Free(); } } private static void AppendLoadDirectiveDiagnostics(DiagnosticBag builder, SyntaxAndDeclarationManager syntaxAndDeclarations, SyntaxTree syntaxTree, Func<IEnumerable<Diagnostic>, IEnumerable<Diagnostic>>? locationFilterOpt = null) { ImmutableArray<LoadDirective> loadDirectives; if (syntaxAndDeclarations.GetLazyState().LoadDirectiveMap.TryGetValue(syntaxTree, out loadDirectives)) { Debug.Assert(!loadDirectives.IsEmpty); foreach (var directive in loadDirectives) { IEnumerable<Diagnostic> diagnostics = directive.Diagnostics; if (locationFilterOpt != null) { diagnostics = locationFilterOpt(diagnostics); } builder.AddRange(diagnostics); } } } // Do the steps in compilation to get the method body diagnostics, but don't actually generate // IL or emit an assembly. private void GetDiagnosticsForAllMethodBodies(BindingDiagnosticBag diagnostics, bool doLowering, CancellationToken cancellationToken) { RoslynDebug.Assert(diagnostics.DiagnosticBag is object); MethodCompiler.CompileMethodBodies( compilation: this, moduleBeingBuiltOpt: doLowering ? (PEModuleBuilder?)CreateModuleBuilder( emitOptions: EmitOptions.Default, debugEntryPoint: null, manifestResources: null, sourceLinkStream: null, embeddedTexts: null, testData: null, diagnostics: diagnostics.DiagnosticBag, cancellationToken: cancellationToken) : null, emittingPdb: false, emitTestCoverageData: false, hasDeclarationErrors: false, emitMethodBodies: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: cancellationToken); DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, diagnostics, cancellationToken); this.ReportUnusedImports(filterTree: null, diagnostics, cancellationToken); } private static bool IsDefinedOrImplementedInSourceTree(Symbol symbol, SyntaxTree tree, TextSpan? span) { if (symbol.IsDefinedInSourceTree(tree, span)) { return true; } if (symbol.Kind == SymbolKind.Method && symbol.IsImplicitlyDeclared && ((MethodSymbol)symbol).MethodKind == MethodKind.Constructor) { // Include implicitly declared constructor if containing type is included return IsDefinedOrImplementedInSourceTree(symbol.ContainingType, tree, span); } return false; } private ImmutableArray<Diagnostic> GetDiagnosticsForMethodBodiesInTree(SyntaxTree tree, TextSpan? span, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); var bindingDiagnostics = new BindingDiagnosticBag(diagnostics); // Report unused directives only if computing diagnostics for the entire tree. // Otherwise we cannot determine if a particular directive is used outside of the given sub-span within the tree. bool reportUnusedUsings = (!span.HasValue || span.Value == tree.GetRoot(cancellationToken).FullSpan) && ReportUnusedImportsInTree(tree); bool recordUsageOfUsingsInAllTrees = false; if (reportUnusedUsings && UsageOfUsingsRecordedInTrees is not null) { foreach (var singleDeclaration in ((SourceNamespaceSymbol)SourceModule.GlobalNamespace).MergedDeclaration.Declarations) { if (singleDeclaration.SyntaxReference.SyntaxTree == tree) { if (singleDeclaration.HasGlobalUsings) { // Global Using directives can be used in any tree. Make sure we collect usage information from all of them. recordUsageOfUsingsInAllTrees = true; } break; } } } if (recordUsageOfUsingsInAllTrees && UsageOfUsingsRecordedInTrees?.IsEmpty == true) { Debug.Assert(reportUnusedUsings); // Simply compile the world compileMethodBodiesAndDocComments(filterTree: null, filterSpan: null, bindingDiagnostics, cancellationToken); _usageOfUsingsRecordedInTrees = null; } else { // Always compile the target tree compileMethodBodiesAndDocComments(filterTree: tree, filterSpan: span, bindingDiagnostics, cancellationToken); if (reportUnusedUsings) { registeredUsageOfUsingsInTree(tree); } // Compile other trees if we need to, but discard diagnostics from them. if (recordUsageOfUsingsInAllTrees) { Debug.Assert(reportUnusedUsings); var discarded = new BindingDiagnosticBag(DiagnosticBag.GetInstance()); Debug.Assert(discarded.DiagnosticBag is object); foreach (var otherTree in SyntaxTrees) { var trackingSet = UsageOfUsingsRecordedInTrees; if (trackingSet is null) { break; } if (!trackingSet.Contains(otherTree)) { compileMethodBodiesAndDocComments(filterTree: otherTree, filterSpan: null, discarded, cancellationToken); registeredUsageOfUsingsInTree(otherTree); discarded.DiagnosticBag.Clear(); } } discarded.DiagnosticBag.Free(); } } if (reportUnusedUsings) { ReportUnusedImports(tree, bindingDiagnostics, cancellationToken); } return diagnostics.ToReadOnlyAndFree(); void compileMethodBodiesAndDocComments(SyntaxTree? filterTree, TextSpan? filterSpan, BindingDiagnosticBag bindingDiagnostics, CancellationToken cancellationToken) { MethodCompiler.CompileMethodBodies( compilation: this, moduleBeingBuiltOpt: null, emittingPdb: false, emitTestCoverageData: false, hasDeclarationErrors: false, emitMethodBodies: false, diagnostics: bindingDiagnostics, filterOpt: filterTree is object ? (Predicate<Symbol>?)(s => IsDefinedOrImplementedInSourceTree(s, filterTree, filterSpan)) : (Predicate<Symbol>?)null, cancellationToken: cancellationToken); DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, bindingDiagnostics, cancellationToken, filterTree, filterSpan); } void registeredUsageOfUsingsInTree(SyntaxTree tree) { var current = UsageOfUsingsRecordedInTrees; while (true) { if (current is null) { break; } var updated = current.Add(tree); if ((object)updated == current) { break; } if (updated.Count == SyntaxTrees.Length) { _usageOfUsingsRecordedInTrees = null; break; } var recent = Interlocked.CompareExchange(ref _usageOfUsingsRecordedInTrees, updated, current); if (recent == (object)current) { break; } current = recent; } } } private ImmutableBindingDiagnostic<AssemblySymbol> GetSourceDeclarationDiagnostics(SyntaxTree? syntaxTree = null, TextSpan? filterSpanWithinTree = null, Func<IEnumerable<Diagnostic>, SyntaxTree, TextSpan?, IEnumerable<Diagnostic>>? locationFilterOpt = null, CancellationToken cancellationToken = default) { UsingsFromOptions.Complete(this, cancellationToken); SourceLocation? location = null; if (syntaxTree != null) { var root = syntaxTree.GetRoot(cancellationToken); location = filterSpanWithinTree.HasValue ? new SourceLocation(syntaxTree, filterSpanWithinTree.Value) : new SourceLocation(root); } Assembly.ForceComplete(location, cancellationToken); if (syntaxTree is null) { // Don't freeze the compilation if we're getting // diagnostics for a single tree _declarationDiagnosticsFrozen = true; // Also freeze generated attribute flags. // Symbols bound after getting the declaration // diagnostics shouldn't need to modify the flags. _needsGeneratedAttributes_IsFrozen = true; } var result = _lazyDeclarationDiagnostics?.AsEnumerable() ?? Enumerable.Empty<Diagnostic>(); if (locationFilterOpt != null) { RoslynDebug.Assert(syntaxTree != null); result = locationFilterOpt(result, syntaxTree, filterSpanWithinTree); } // NOTE: Concatenate the CLS diagnostics *after* filtering by tree/span, because they're already filtered. ImmutableBindingDiagnostic<AssemblySymbol> clsDiagnostics = GetClsComplianceDiagnostics(syntaxTree, filterSpanWithinTree, cancellationToken); return new ImmutableBindingDiagnostic<AssemblySymbol>(result.AsImmutable().Concat(clsDiagnostics.Diagnostics), clsDiagnostics.Dependencies); } private ImmutableBindingDiagnostic<AssemblySymbol> GetClsComplianceDiagnostics(SyntaxTree? syntaxTree, TextSpan? filterSpanWithinTree, CancellationToken cancellationToken) { if (syntaxTree != null) { var builder = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); ClsComplianceChecker.CheckCompliance(this, builder, cancellationToken, syntaxTree, filterSpanWithinTree); return builder.ToReadOnlyAndFree(); } if (_lazyClsComplianceDiagnostics.IsDefault || _lazyClsComplianceDependencies.IsDefault) { var builder = BindingDiagnosticBag.GetInstance(); ClsComplianceChecker.CheckCompliance(this, builder, cancellationToken); var result = builder.ToReadOnlyAndFree(); ImmutableInterlocked.InterlockedInitialize(ref _lazyClsComplianceDependencies, result.Dependencies); ImmutableInterlocked.InterlockedInitialize(ref _lazyClsComplianceDiagnostics, result.Diagnostics); } Debug.Assert(!_lazyClsComplianceDependencies.IsDefault); Debug.Assert(!_lazyClsComplianceDiagnostics.IsDefault); return new ImmutableBindingDiagnostic<AssemblySymbol>(_lazyClsComplianceDiagnostics, _lazyClsComplianceDependencies); } private static IEnumerable<Diagnostic> FilterDiagnosticsByLocation(IEnumerable<Diagnostic> diagnostics, SyntaxTree tree, TextSpan? filterSpanWithinTree) { foreach (var diagnostic in diagnostics) { if (diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree)) { yield return diagnostic; } } } internal ImmutableArray<Diagnostic> GetDiagnosticsForSyntaxTree( CompilationStage stage, SyntaxTree syntaxTree, TextSpan? filterSpanWithinTree, bool includeEarlierStages, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); DiagnosticBag? builder = DiagnosticBag.GetInstance(); if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages)) { AppendLoadDirectiveDiagnostics(builder, _syntaxAndDeclarations, syntaxTree, diagnostics => FilterDiagnosticsByLocation(diagnostics, syntaxTree, filterSpanWithinTree)); var syntaxDiagnostics = syntaxTree.GetDiagnostics(cancellationToken); syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, syntaxTree, filterSpanWithinTree); builder.AddRange(syntaxDiagnostics); } cancellationToken.ThrowIfCancellationRequested(); if (stage == CompilationStage.Declare || (stage > CompilationStage.Declare && includeEarlierStages)) { var declarationDiagnostics = GetSourceDeclarationDiagnostics(syntaxTree, filterSpanWithinTree, FilterDiagnosticsByLocation, cancellationToken); // re-enabling/fixing the below assert is tracked by https://github.com/dotnet/roslyn/issues/21020 // Debug.Assert(declarationDiagnostics.All(d => d.HasIntersectingLocation(syntaxTree, filterSpanWithinTree))); builder.AddRange(declarationDiagnostics.Diagnostics); } cancellationToken.ThrowIfCancellationRequested(); if (stage == CompilationStage.Compile || (stage > CompilationStage.Compile && includeEarlierStages)) { //remove some errors that don't have locations in the tree, like "no suitable main method." //Members in trees other than the one being examined are not compiled. This includes field //initializers which can result in 'field is never initialized' warnings for fields in partial //types when the field is in a different source file than the one for which we're getting diagnostics. //For that reason the bag must be also filtered by tree. IEnumerable<Diagnostic> methodBodyDiagnostics = GetDiagnosticsForMethodBodiesInTree(syntaxTree, filterSpanWithinTree, cancellationToken); // TODO: Enable the below commented assert and remove the filtering code in the next line. // GetDiagnosticsForMethodBodiesInTree seems to be returning diagnostics with locations that don't satisfy the filter tree/span, this must be fixed. // Debug.Assert(methodBodyDiagnostics.All(d => DiagnosticContainsLocation(d, syntaxTree, filterSpanWithinTree))); methodBodyDiagnostics = FilterDiagnosticsByLocation(methodBodyDiagnostics, syntaxTree, filterSpanWithinTree); builder.AddRange(methodBodyDiagnostics); } // Before returning diagnostics, we filter warnings // to honor the compiler options (/nowarn, /warnaserror and /warn) and the pragmas. var result = DiagnosticBag.GetInstance(); FilterAndAppendAndFreeDiagnostics(result, ref builder, cancellationToken); return result.ToReadOnlyAndFree<Diagnostic>(); } #endregion #region Resources protected override void AppendDefaultVersionResource(Stream resourceStream) { var sourceAssembly = SourceAssembly; string fileVersion = sourceAssembly.FileVersion ?? sourceAssembly.Identity.Version.ToString(); Win32ResourceConversions.AppendVersionToResourceStream(resourceStream, !this.Options.OutputKind.IsApplication(), fileVersion: fileVersion, originalFileName: this.SourceModule.Name, internalName: this.SourceModule.Name, productVersion: sourceAssembly.InformationalVersion ?? fileVersion, fileDescription: sourceAssembly.Title ?? " ", //alink would give this a blank if nothing was supplied. assemblyVersion: sourceAssembly.Identity.Version, legalCopyright: sourceAssembly.Copyright ?? " ", //alink would give this a blank if nothing was supplied. legalTrademarks: sourceAssembly.Trademark, productName: sourceAssembly.Product, comments: sourceAssembly.Description, companyName: sourceAssembly.Company); } #endregion #region Emit internal override byte LinkerMajorVersion => 0x30; internal override bool IsDelaySigned { get { return SourceAssembly.IsDelaySigned; } } internal override StrongNameKeys StrongNameKeys { get { return SourceAssembly.StrongNameKeys; } } internal override CommonPEModuleBuilder? CreateModuleBuilder( EmitOptions emitOptions, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, IEnumerable<ResourceDescription>? manifestResources, CompilationTestData? testData, DiagnosticBag diagnostics, CancellationToken cancellationToken) { Debug.Assert(!IsSubmission || HasCodeToEmit() || (emitOptions == EmitOptions.Default && debugEntryPoint is null && sourceLinkStream is null && embeddedTexts is null && manifestResources is null && testData is null)); string? runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions, diagnostics); if (runtimeMDVersion == null) { return null; } var moduleProps = ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion); if (manifestResources == null) { manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>(); } PEModuleBuilder moduleBeingBuilt; if (_options.OutputKind.IsNetModule()) { moduleBeingBuilt = new PENetModuleBuilder( (SourceModuleSymbol)SourceModule, emitOptions, moduleProps, manifestResources); } else { var kind = _options.OutputKind.IsValid() ? _options.OutputKind : OutputKind.DynamicallyLinkedLibrary; moduleBeingBuilt = new PEAssemblyBuilder( SourceAssembly, emitOptions, kind, moduleProps, manifestResources); } if (debugEntryPoint != null) { moduleBeingBuilt.SetDebugEntryPoint(debugEntryPoint.GetSymbol(), diagnostics); } moduleBeingBuilt.SourceLinkStreamOpt = sourceLinkStream; if (embeddedTexts != null) { moduleBeingBuilt.EmbeddedTexts = embeddedTexts; } // testData is only passed when running tests. if (testData != null) { moduleBeingBuilt.SetMethodTestData(testData.Methods); testData.Module = moduleBeingBuilt; } return moduleBeingBuilt; } internal override bool CompileMethods( CommonPEModuleBuilder moduleBuilder, bool emittingPdb, bool emitMetadataOnly, bool emitTestCoverageData, DiagnosticBag diagnostics, Predicate<ISymbolInternal>? filterOpt, CancellationToken cancellationToken) { // The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that the emitter // does not attempt to emit if there are declaration errors (but we do insert all errors from method body binding...) PooledHashSet<int>? excludeDiagnostics = null; if (emitMetadataOnly) { excludeDiagnostics = PooledHashSet<int>.GetInstance(); excludeDiagnostics.Add((int)ErrorCode.ERR_ConcreteMissingBody); } bool hasDeclarationErrors = !FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, true, cancellationToken), excludeDiagnostics, cancellationToken); excludeDiagnostics?.Free(); // TODO (tomat): NoPIA: // EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(this) var moduleBeingBuilt = (PEModuleBuilder)moduleBuilder; if (emitMetadataOnly) { if (hasDeclarationErrors) { return false; } if (moduleBeingBuilt.SourceModule.HasBadAttributes) { // If there were errors but no declaration diagnostics, explicitly add a "Failed to emit module" error. diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((Cci.INamedEntity)moduleBeingBuilt).Name, new LocalizableResourceString(nameof(CodeAnalysisResources.ModuleHasInvalidAttributes), CodeAnalysisResources.ResourceManager, typeof(CodeAnalysisResources))); return false; } SynthesizedMetadataCompiler.ProcessSynthesizedMembers(this, moduleBeingBuilt, cancellationToken); } else { if ((emittingPdb || emitTestCoverageData) && !CreateDebugDocuments(moduleBeingBuilt.DebugDocumentsBuilder, moduleBeingBuilt.EmbeddedTexts, diagnostics)) { return false; } // Perform initial bind of method bodies in spite of earlier errors. This is the same // behavior as when calling GetDiagnostics() // Use a temporary bag so we don't have to refilter pre-existing diagnostics. DiagnosticBag? methodBodyDiagnosticBag = DiagnosticBag.GetInstance(); Debug.Assert(moduleBeingBuilt is object); MethodCompiler.CompileMethodBodies( this, moduleBeingBuilt, emittingPdb, emitTestCoverageData, hasDeclarationErrors, emitMethodBodies: true, diagnostics: new BindingDiagnosticBag(methodBodyDiagnosticBag), filterOpt: filterOpt, cancellationToken: cancellationToken); if (!hasDeclarationErrors && !CommonCompiler.HasUnsuppressableErrors(methodBodyDiagnosticBag)) { GenerateModuleInitializer(moduleBeingBuilt, methodBodyDiagnosticBag); } bool hasMethodBodyError = !FilterAndAppendAndFreeDiagnostics(diagnostics, ref methodBodyDiagnosticBag, cancellationToken); if (hasDeclarationErrors || hasMethodBodyError) { return false; } } return true; } private void GenerateModuleInitializer(PEModuleBuilder moduleBeingBuilt, DiagnosticBag methodBodyDiagnosticBag) { Debug.Assert(_declarationDiagnosticsFrozen); if (_moduleInitializerMethods is object) { var ilBuilder = new ILBuilder(moduleBeingBuilt, new LocalSlotManager(slotAllocator: null), OptimizationLevel.Release, areLocalsZeroed: false); foreach (MethodSymbol method in _moduleInitializerMethods.OrderBy<MethodSymbol>(LexicalOrderSymbolComparer.Instance)) { ilBuilder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); ilBuilder.EmitToken( moduleBeingBuilt.Translate(method, methodBodyDiagnosticBag, needDeclaration: true), CSharpSyntaxTree.Dummy.GetRoot(), methodBodyDiagnosticBag); } ilBuilder.EmitRet(isVoid: true); ilBuilder.Realize(); moduleBeingBuilt.RootModuleType.SetStaticConstructorBody(ilBuilder.RealizedIL); } } internal override bool GenerateResourcesAndDocumentationComments( CommonPEModuleBuilder moduleBuilder, Stream? xmlDocStream, Stream? win32Resources, bool useRawWin32Resources, string? outputNameOverride, DiagnosticBag diagnostics, CancellationToken cancellationToken) { // Use a temporary bag so we don't have to refilter pre-existing diagnostics. DiagnosticBag? resourceDiagnostics = DiagnosticBag.GetInstance(); SetupWin32Resources(moduleBuilder, win32Resources, useRawWin32Resources, resourceDiagnostics); ReportManifestResourceDuplicates( moduleBuilder.ManifestResources, SourceAssembly.Modules.Skip(1).Select(m => m.Name), //all modules except the first one AddedModulesResourceNames(resourceDiagnostics), resourceDiagnostics); if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref resourceDiagnostics, cancellationToken)) { return false; } cancellationToken.ThrowIfCancellationRequested(); // Use a temporary bag so we don't have to refilter pre-existing diagnostics. DiagnosticBag? xmlDiagnostics = DiagnosticBag.GetInstance(); string? assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, extension: null); DocumentationCommentCompiler.WriteDocumentationCommentXml(this, assemblyName, xmlDocStream, new BindingDiagnosticBag(xmlDiagnostics), cancellationToken); return FilterAndAppendAndFreeDiagnostics(diagnostics, ref xmlDiagnostics, cancellationToken); } private IEnumerable<string> AddedModulesResourceNames(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) { var m = (Symbols.Metadata.PE.PEModuleSymbol)modules[i]; ImmutableArray<EmbeddedResource> resources; try { resources = m.Module.GetEmbeddedResourcesOrThrow(); } catch (BadImageFormatException) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, m), NoLocation.Singleton); continue; } foreach (var resource in resources) { yield return resource.Name; } } } internal override EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken) { return EmitHelpers.EmitDifference( this, baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData, cancellationToken); } internal string? GetRuntimeMetadataVersion(EmitOptions emitOptions, DiagnosticBag diagnostics) { string? runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions); if (runtimeMDVersion != null) { return runtimeMDVersion; } DiagnosticBag? runtimeMDVersionDiagnostics = DiagnosticBag.GetInstance(); runtimeMDVersionDiagnostics.Add(ErrorCode.WRN_NoRuntimeMetadataVersion, NoLocation.Singleton); if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref runtimeMDVersionDiagnostics, CancellationToken.None)) { return null; } return string.Empty; //prevent emitter from crashing. } private string? GetRuntimeMetadataVersion(EmitOptions emitOptions) { var corAssembly = Assembly.CorLibrary as Symbols.Metadata.PE.PEAssemblySymbol; if (corAssembly is object) { return corAssembly.Assembly.ManifestModule.MetadataVersion; } return emitOptions.RuntimeMetadataVersion; } internal override void AddDebugSourceDocumentsForChecksumDirectives( DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics) { var checksumDirectives = tree.GetRoot().GetDirectives(d => d.Kind() == SyntaxKind.PragmaChecksumDirectiveTrivia && !d.ContainsDiagnostics); foreach (var directive in checksumDirectives) { var checksumDirective = (PragmaChecksumDirectiveTriviaSyntax)directive; var path = checksumDirective.File.ValueText; var checksumText = checksumDirective.Bytes.ValueText; var normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(path, basePath: tree.FilePath); var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath); // duplicate checksum pragmas are valid as long as values match // if we have seen this document already, check for matching values. if (existingDoc != null) { // pragma matches a file path on an actual tree. // Dev12 compiler just ignores the pragma in this case which means that // checksum of the actual tree always wins and no warning is given. // We will continue doing the same. if (existingDoc.IsComputedChecksum) { continue; } var sourceInfo = existingDoc.GetSourceInfo(); if (ChecksumMatches(checksumText, sourceInfo.Checksum)) { var guid = Guid.Parse(checksumDirective.Guid.ValueText); if (guid == sourceInfo.ChecksumAlgorithmId) { // all parts match, nothing to do continue; } } // did not match to an existing document // produce a warning and ignore the pragma diagnostics.Add(ErrorCode.WRN_ConflictingChecksum, new SourceLocation(checksumDirective), path); } else { var newDocument = new Cci.DebugSourceDocument( normalizedPath, Cci.DebugSourceDocument.CorSymLanguageTypeCSharp, MakeChecksumBytes(checksumText), Guid.Parse(checksumDirective.Guid.ValueText)); documentsBuilder.AddDebugDocument(newDocument); } } } private static bool ChecksumMatches(string bytesText, ImmutableArray<byte> bytes) { if (bytesText.Length != bytes.Length * 2) { return false; } for (int i = 0, len = bytesText.Length / 2; i < len; i++) { // 1A in text becomes 0x1A var b = SyntaxFacts.HexValue(bytesText[i * 2]) * 16 + SyntaxFacts.HexValue(bytesText[i * 2 + 1]); if (b != bytes[i]) { return false; } } return true; } private static ImmutableArray<byte> MakeChecksumBytes(string bytesText) { int length = bytesText.Length / 2; var builder = ArrayBuilder<byte>.GetInstance(length); for (int i = 0; i < length; i++) { // 1A in text becomes 0x1A var b = SyntaxFacts.HexValue(bytesText[i * 2]) * 16 + SyntaxFacts.HexValue(bytesText[i * 2 + 1]); builder.Add((byte)b); } return builder.ToImmutableAndFree(); } internal override Guid DebugSourceDocumentLanguageId => Cci.DebugSourceDocument.CorSymLanguageTypeCSharp; internal override bool HasCodeToEmit() { foreach (var syntaxTree in this.SyntaxTrees) { var unit = syntaxTree.GetCompilationUnitRoot(); if (unit.Members.Count > 0) { return true; } } return false; } #endregion #region Common Members protected override Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences) { return WithReferences(newReferences); } protected override Compilation CommonWithAssemblyName(string? assemblyName) { return WithAssemblyName(assemblyName); } protected override IAssemblySymbol CommonAssembly { get { return this.Assembly.GetPublicSymbol(); } } protected override INamespaceSymbol CommonGlobalNamespace { get { return this.GlobalNamespace.GetPublicSymbol(); } } protected override CompilationOptions CommonOptions { get { return _options; } } protected override SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) { return this.GetSemanticModel((SyntaxTree)syntaxTree, ignoreAccessibility); } protected override ImmutableArray<SyntaxTree> CommonSyntaxTrees { get { return this.SyntaxTrees; } } protected override Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees) { return this.AddSyntaxTrees(trees); } protected override Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees) { return this.RemoveSyntaxTrees(trees); } protected override Compilation CommonRemoveAllSyntaxTrees() { return this.RemoveAllSyntaxTrees(); } protected override Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree? newTree) { return this.ReplaceSyntaxTree(oldTree, newTree); } protected override Compilation CommonWithOptions(CompilationOptions options) { return this.WithOptions((CSharpCompilationOptions)options); } protected override Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info) { return this.WithScriptCompilationInfo((CSharpScriptCompilationInfo?)info); } protected override bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree) { return this.ContainsSyntaxTree(syntaxTree); } protected override ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference) { return this.GetAssemblyOrModuleSymbol(reference).GetPublicSymbol(); } protected override Compilation CommonClone() { return this.Clone(); } protected override IModuleSymbol CommonSourceModule { get { return this.SourceModule.GetPublicSymbol(); } } private protected override INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType) { return this.GetSpecialType(specialType); } protected override INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol) { return this.GetCompilationNamespace(namespaceSymbol).GetPublicSymbol(); } protected override INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName) { return this.GetTypeByMetadataName(metadataName).GetPublicSymbol(); } protected override INamedTypeSymbol? CommonScriptClass { get { return this.ScriptClass.GetPublicSymbol(); } } protected override IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, CodeAnalysis.NullableAnnotation elementNullableAnnotation) { return CreateArrayTypeSymbol(elementType.EnsureCSharpSymbolOrNull(nameof(elementType)), rank, elementNullableAnnotation.ToInternalAnnotation()).GetPublicSymbol(); } protected override IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType) { return CreatePointerTypeSymbol(elementType.EnsureCSharpSymbolOrNull(nameof(elementType)), elementType.NullableAnnotation.ToInternalAnnotation()).GetPublicSymbol(); } protected override IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol( ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, SignatureCallingConvention callingConvention, ImmutableArray<INamedTypeSymbol> callingConventionTypes) { if (returnType is null) { throw new ArgumentNullException(nameof(returnType)); } if (parameterTypes.IsDefault) { throw new ArgumentNullException(nameof(parameterTypes)); } for (int i = 0; i < parameterTypes.Length; i++) { if (parameterTypes[i] is null) { throw new ArgumentNullException($"{nameof(parameterTypes)}[{i}]"); } } if (parameterRefKinds.IsDefault) { throw new ArgumentNullException(nameof(parameterRefKinds)); } if (parameterRefKinds.Length != parameterTypes.Length) { // Given {0} parameter types and {1} parameter ref kinds. These must be the same. throw new ArgumentException(string.Format(CSharpResources.NotSameNumberParameterTypesAndRefKinds, parameterTypes.Length, parameterRefKinds.Length)); } if (returnRefKind == RefKind.Out) { //'RefKind.Out' is not a valid ref kind for a return type. throw new ArgumentException(CSharpResources.OutIsNotValidForReturn); } if (callingConvention != SignatureCallingConvention.Unmanaged && !callingConventionTypes.IsDefaultOrEmpty) { throw new ArgumentException(string.Format(CSharpResources.CallingConventionTypesRequireUnmanaged, nameof(callingConventionTypes), nameof(callingConvention))); } if (!callingConvention.IsValid()) { throw new ArgumentOutOfRangeException(nameof(callingConvention)); } var returnTypeWithAnnotations = TypeWithAnnotations.Create(returnType.EnsureCSharpSymbolOrNull(nameof(returnType)), returnType.NullableAnnotation.ToInternalAnnotation()); var parameterTypesWithAnnotations = parameterTypes.SelectAsArray( type => TypeWithAnnotations.Create(type.EnsureCSharpSymbolOrNull(nameof(parameterTypes)), type.NullableAnnotation.ToInternalAnnotation())); var internalCallingConvention = callingConvention.FromSignatureConvention(); var conventionModifiers = internalCallingConvention == CallingConvention.Unmanaged && !callingConventionTypes.IsDefaultOrEmpty ? callingConventionTypes.SelectAsArray((type, i, @this) => getCustomModifierForType(type, @this, i), this) : ImmutableArray<CustomModifier>.Empty; return FunctionPointerTypeSymbol.CreateFromParts( internalCallingConvention, conventionModifiers, returnTypeWithAnnotations, returnRefKind: returnRefKind, parameterTypes: parameterTypesWithAnnotations, parameterRefKinds: parameterRefKinds, compilation: this).GetPublicSymbol(); static CustomModifier getCustomModifierForType(INamedTypeSymbol type, CSharpCompilation @this, int index) { if (type is null) { throw new ArgumentNullException($"{nameof(callingConventionTypes)}[{index}]"); } var internalType = type.EnsureCSharpSymbolOrNull($"{nameof(callingConventionTypes)}[{index}]"); if (!FunctionPointerTypeSymbol.IsCallingConventionModifier(internalType) || @this.Assembly.CorLibrary != internalType.ContainingAssembly) { throw new ArgumentException(string.Format(CSharpResources.CallingConventionTypeIsInvalid, type.ToDisplayString())); } return CSharpCustomModifier.CreateOptional(internalType); } } protected override INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed) { return CreateNativeIntegerTypeSymbol(signed).GetPublicSymbol(); } internal new NamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed) { return GetSpecialType(signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr).AsNativeInteger(); } protected override INamedTypeSymbol CommonCreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<CodeAnalysis.NullableAnnotation> elementNullableAnnotations) { var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(elementTypes.Length); for (int i = 0; i < elementTypes.Length; i++) { ITypeSymbol typeSymbol = elementTypes[i]; var elementType = typeSymbol.EnsureCSharpSymbolOrNull($"{nameof(elementTypes)}[{i}]"); var annotation = (elementNullableAnnotations.IsDefault ? typeSymbol.NullableAnnotation : elementNullableAnnotations[i]).ToInternalAnnotation(); typesBuilder.Add(TypeWithAnnotations.Create(elementType, annotation)); } return NamedTypeSymbol.CreateTuple( locationOpt: null, // no location for the type declaration elementTypesWithAnnotations: typesBuilder.ToImmutableAndFree(), elementLocations: elementLocations, elementNames: elementNames, compilation: this, shouldCheckConstraints: false, includeNullability: false, errorPositions: default).GetPublicSymbol(); } protected override INamedTypeSymbol CommonCreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<CodeAnalysis.NullableAnnotation> elementNullableAnnotations) { NamedTypeSymbol csharpUnderlyingTuple = underlyingType.EnsureCSharpSymbolOrNull(nameof(underlyingType)); if (!csharpUnderlyingTuple.IsTupleTypeOfCardinality(out int cardinality)) { throw new ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, nameof(underlyingType)); } elementNames = CheckTupleElementNames(cardinality, elementNames); CheckTupleElementLocations(cardinality, elementLocations); CheckTupleElementNullableAnnotations(cardinality, elementNullableAnnotations); var tupleType = NamedTypeSymbol.CreateTuple( csharpUnderlyingTuple, elementNames, elementLocations: elementLocations!); if (!elementNullableAnnotations.IsDefault) { tupleType = tupleType.WithElementTypes( tupleType.TupleElementTypesWithAnnotations.ZipAsArray( elementNullableAnnotations, (t, a) => TypeWithAnnotations.Create(t.Type, a.ToInternalAnnotation()))); } return tupleType.GetPublicSymbol(); } protected override INamedTypeSymbol CommonCreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<Location> memberLocations, ImmutableArray<bool> memberIsReadOnly, ImmutableArray<CodeAnalysis.NullableAnnotation> memberNullableAnnotations) { for (int i = 0, n = memberTypes.Length; i < n; i++) { memberTypes[i].EnsureCSharpSymbolOrNull($"{nameof(memberTypes)}[{i}]"); } if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Any(v => !v)) { throw new ArgumentException($"Non-ReadOnly members are not supported in C# anonymous types."); } var fields = ArrayBuilder<AnonymousTypeField>.GetInstance(); for (int i = 0, n = memberTypes.Length; i < n; i++) { var type = memberTypes[i].GetSymbol(); var name = memberNames[i]; var location = memberLocations.IsDefault ? Location.None : memberLocations[i]; var nullableAnnotation = memberNullableAnnotations.IsDefault ? NullableAnnotation.Oblivious : memberNullableAnnotations[i].ToInternalAnnotation(); fields.Add(new AnonymousTypeField(name, location, TypeWithAnnotations.Create(type, nullableAnnotation))); } var descriptor = new AnonymousTypeDescriptor(fields.ToImmutableAndFree(), Location.None); return this.AnonymousTypeManager.ConstructAnonymousTypeSymbol(descriptor).GetPublicSymbol(); } protected override ITypeSymbol CommonDynamicType { get { return DynamicType.GetPublicSymbol(); } } protected override INamedTypeSymbol CommonObjectType { get { return this.ObjectType.GetPublicSymbol(); } } protected override IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken) { return this.GetEntryPoint(cancellationToken).GetPublicSymbol(); } internal override int CompareSourceLocations(Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource); Debug.Assert(loc2.IsInSource); var comparison = CompareSyntaxTreeOrdering(loc1.SourceTree!, loc2.SourceTree!); if (comparison != 0) { return comparison; } return loc1.SourceSpan.Start - loc2.SourceSpan.Start; } internal override int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2) { var comparison = CompareSyntaxTreeOrdering(loc1.SyntaxTree, loc2.SyntaxTree); if (comparison != 0) { return comparison; } return loc1.Span.Start - loc2.Span.Start; } /// <summary> /// Return true if there is a source declaration symbol name that meets given predicate. /// </summary> public override bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return DeclarationTable.ContainsName(this.MergedRootDeclaration, predicate, filter, cancellationToken); } /// <summary> /// Return source declaration symbols whose name meets given predicate. /// </summary> public override IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return new PredicateSymbolSearcher(this, filter, predicate, cancellationToken).GetSymbolsWithName().GetPublicSymbols()!; } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Return true if there is a source declaration symbol name that matches the provided name. /// This will be faster than <see cref="ContainsSymbolsWithName(Func{string, bool}, SymbolFilter, CancellationToken)"/> /// when predicate is just a simple string check. /// </summary> public override bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return DeclarationTable.ContainsName(this.MergedRootDeclaration, name, filter, cancellationToken); } /// <summary> /// Return source declaration symbols whose name matches the provided name. This will be /// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter, /// CancellationToken)"/> when predicate is just a simple string check. <paramref /// name="name"/> is case sensitive. /// </summary> public override IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { return GetSymbolsWithNameCore(name, filter, cancellationToken).GetPublicSymbols()!; } internal IEnumerable<Symbol> GetSymbolsWithNameCore(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return new NameSymbolSearcher(this, filter, name, cancellationToken).GetSymbolsWithName(); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters #endregion /// <summary> /// Returns if the compilation has all of the members necessary to emit metadata about /// dynamic types. /// </summary> /// <returns></returns> internal bool HasDynamicEmitAttributes(BindingDiagnosticBag diagnostics, Location location) { return Binder.GetWellKnownTypeMember(this, WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor, diagnostics, location) is object && Binder.GetWellKnownTypeMember(this, WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, diagnostics, location) is object; } internal bool HasTupleNamesAttributes(BindingDiagnosticBag diagnostics, Location location) => Binder.GetWellKnownTypeMember(this, WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, diagnostics, location) is object; /// <summary> /// Returns whether the compilation has the Boolean type and if it's good. /// </summary> /// <returns>Returns true if Boolean is present and healthy.</returns> internal bool CanEmitBoolean() => CanEmitSpecialType(SpecialType.System_Boolean); internal bool CanEmitSpecialType(SpecialType type) { var typeSymbol = GetSpecialType(type); var diagnostic = typeSymbol.GetUseSiteInfo().DiagnosticInfo; return (diagnostic == null) || (diagnostic.Severity != DiagnosticSeverity.Error); } internal bool EmitNullablePublicOnly { get { if (!_lazyEmitNullablePublicOnly.HasValue()) { bool value = SyntaxTrees.FirstOrDefault()?.Options?.Features?.ContainsKey("nullablePublicOnly") == true; _lazyEmitNullablePublicOnly = value.ToThreeState(); } return _lazyEmitNullablePublicOnly.Value(); } } internal bool ShouldEmitNullableAttributes(Symbol symbol) { RoslynDebug.Assert(symbol is object); Debug.Assert(symbol.IsDefinition); if (symbol.ContainingModule != SourceModule) { return false; } if (!EmitNullablePublicOnly) { return true; } // For symbols that do not have explicit accessibility in metadata, // use the accessibility of the container. symbol = getExplicitAccessibilitySymbol(symbol); if (!AccessCheck.IsEffectivelyPublicOrInternal(symbol, out bool isInternal)) { return false; } return !isInternal || SourceAssembly.InternalsAreVisible; static Symbol getExplicitAccessibilitySymbol(Symbol symbol) { while (true) { switch (symbol.Kind) { case SymbolKind.Parameter: case SymbolKind.TypeParameter: case SymbolKind.Property: case SymbolKind.Event: symbol = symbol.ContainingSymbol; break; default: return symbol; } } } } internal override AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter) { Func<SyntaxNode, SyntaxKind> getKind = node => node.Kind(); Func<SyntaxTrivia, bool> isComment = trivia => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia; return new AnalyzerDriver<SyntaxKind>(analyzers, getKind, analyzerManager, severityFilter, isComment); } internal void SymbolDeclaredEvent(Symbol symbol) { EventQueue?.TryEnqueue(new SymbolDeclaredCompilationEvent(this, symbol.GetPublicSymbol())); } internal override void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder) { // LanguageVersion should already be mapped to a specific version Debug.Assert(LanguageVersion == LanguageVersion.MapSpecifiedToEffectiveVersion()); WriteValue(CompilationOptionNames.LanguageVersion, LanguageVersion.ToDisplayString()); if (Options.CheckOverflow) { WriteValue(CompilationOptionNames.Checked, Options.CheckOverflow.ToString()); } if (Options.NullableContextOptions != NullableContextOptions.Disable) { WriteValue(CompilationOptionNames.Nullable, Options.NullableContextOptions.ToString()); } if (Options.AllowUnsafe) { WriteValue(CompilationOptionNames.Unsafe, Options.AllowUnsafe.ToString()); } var preprocessorSymbols = GetPreprocessorSymbols(); if (preprocessorSymbols.Any()) { WriteValue(CompilationOptionNames.Define, string.Join(",", preprocessorSymbols)); } void WriteValue(string key, string value) { builder.WriteUTF8(key); builder.WriteByte(0); builder.WriteUTF8(value); builder.WriteByte(0); } } private ImmutableArray<string> GetPreprocessorSymbols() { CSharpSyntaxTree? firstTree = (CSharpSyntaxTree?)SyntaxTrees.FirstOrDefault(); if (firstTree is null) { return ImmutableArray<string>.Empty; } return firstTree.Options.PreprocessorSymbolNames.ToImmutableArray(); } /// <summary> /// Determine if enum arrays can be initialized using block initialization. /// </summary> /// <returns>True if it's safe to use block initialization for enum arrays.</returns> /// <remarks> /// In NetFx 4.0, block array initializers do not work on all combinations of {32/64 X Debug/Retail} when array elements are enums. /// This is fixed in 4.5 thus enabling block array initialization for a very common case. /// We look for the presence of <see cref="System.Runtime.GCLatencyMode.SustainedLowLatency"/> which was introduced in .NET Framework 4.5 /// </remarks> internal bool EnableEnumArrayBlockInitialization { get { var sustainedLowLatency = GetWellKnownTypeMember(WellKnownMember.System_Runtime_GCLatencyMode__SustainedLowLatency); return sustainedLowLatency != null && sustainedLowLatency.ContainingAssembly == Assembly.CorLibrary; } } private abstract class AbstractSymbolSearcher { private readonly PooledDictionary<Declaration, NamespaceOrTypeSymbol> _cache; private readonly CSharpCompilation _compilation; private readonly bool _includeNamespace; private readonly bool _includeType; private readonly bool _includeMember; private readonly CancellationToken _cancellationToken; protected AbstractSymbolSearcher( CSharpCompilation compilation, SymbolFilter filter, CancellationToken cancellationToken) { _cache = PooledDictionary<Declaration, NamespaceOrTypeSymbol>.GetInstance(); _compilation = compilation; _includeNamespace = (filter & SymbolFilter.Namespace) == SymbolFilter.Namespace; _includeType = (filter & SymbolFilter.Type) == SymbolFilter.Type; _includeMember = (filter & SymbolFilter.Member) == SymbolFilter.Member; _cancellationToken = cancellationToken; } protected abstract bool Matches(string name); protected abstract bool ShouldCheckTypeForMembers(MergedTypeDeclaration current); public IEnumerable<Symbol> GetSymbolsWithName() { var result = new HashSet<Symbol>(); var spine = ArrayBuilder<MergedNamespaceOrTypeDeclaration>.GetInstance(); AppendSymbolsWithName(spine, _compilation.MergedRootDeclaration, result); spine.Free(); _cache.Free(); return result; } private void AppendSymbolsWithName( ArrayBuilder<MergedNamespaceOrTypeDeclaration> spine, MergedNamespaceOrTypeDeclaration current, HashSet<Symbol> set) { if (current.Kind == DeclarationKind.Namespace) { if (_includeNamespace && Matches(current.Name)) { var container = GetSpineSymbol(spine); var symbol = GetSymbol(container, current); if (symbol != null) { set.Add(symbol); } } } else { if (_includeType && Matches(current.Name)) { var container = GetSpineSymbol(spine); var symbol = GetSymbol(container, current); if (symbol != null) { set.Add(symbol); } } if (_includeMember) { var typeDeclaration = (MergedTypeDeclaration)current; if (ShouldCheckTypeForMembers(typeDeclaration)) { AppendMemberSymbolsWithName(spine, typeDeclaration, set); } } } spine.Add(current); foreach (var child in current.Children) { if (child is MergedNamespaceOrTypeDeclaration mergedNamespaceOrType) { if (_includeMember || _includeType || child.Kind == DeclarationKind.Namespace) { AppendSymbolsWithName(spine, mergedNamespaceOrType, set); } } } // pop last one spine.RemoveAt(spine.Count - 1); } private void AppendMemberSymbolsWithName( ArrayBuilder<MergedNamespaceOrTypeDeclaration> spine, MergedTypeDeclaration current, HashSet<Symbol> set) { _cancellationToken.ThrowIfCancellationRequested(); spine.Add(current); var container = GetSpineSymbol(spine); if (container != null) { foreach (var member in container.GetMembers()) { if (!member.IsTypeOrTypeAlias() && (member.CanBeReferencedByName || member.IsExplicitInterfaceImplementation() || member.IsIndexer()) && Matches(member.Name)) { set.Add(member); } } } spine.RemoveAt(spine.Count - 1); } protected NamespaceOrTypeSymbol? GetSpineSymbol(ArrayBuilder<MergedNamespaceOrTypeDeclaration> spine) { if (spine.Count == 0) { return null; } var symbol = GetCachedSymbol(spine[spine.Count - 1]); if (symbol != null) { return symbol; } NamespaceOrTypeSymbol? current = _compilation.GlobalNamespace; for (var i = 1; i < spine.Count; i++) { current = GetSymbol(current, spine[i]); } return current; } private NamespaceOrTypeSymbol? GetCachedSymbol(MergedNamespaceOrTypeDeclaration declaration) => _cache.TryGetValue(declaration, out NamespaceOrTypeSymbol? symbol) ? symbol : null; private NamespaceOrTypeSymbol? GetSymbol(NamespaceOrTypeSymbol? container, MergedNamespaceOrTypeDeclaration declaration) { if (container == null) { return _compilation.GlobalNamespace; } if (declaration.Kind == DeclarationKind.Namespace) { AddCache(container.GetMembers(declaration.Name).OfType<NamespaceOrTypeSymbol>()); } else { AddCache(container.GetTypeMembers(declaration.Name)); } return GetCachedSymbol(declaration); } private void AddCache(IEnumerable<NamespaceOrTypeSymbol> symbols) { foreach (var symbol in symbols) { var mergedNamespace = symbol as MergedNamespaceSymbol; if (mergedNamespace != null) { _cache[mergedNamespace.ConstituentNamespaces.OfType<SourceNamespaceSymbol>().First().MergedDeclaration] = symbol; continue; } var sourceNamespace = symbol as SourceNamespaceSymbol; if (sourceNamespace != null) { _cache[sourceNamespace.MergedDeclaration] = sourceNamespace; continue; } var sourceType = symbol as SourceMemberContainerTypeSymbol; if (sourceType is object) { _cache[sourceType.MergedDeclaration] = sourceType; } } } } private class PredicateSymbolSearcher : AbstractSymbolSearcher { private readonly Func<string, bool> _predicate; public PredicateSymbolSearcher( CSharpCompilation compilation, SymbolFilter filter, Func<string, bool> predicate, CancellationToken cancellationToken) : base(compilation, filter, cancellationToken) { _predicate = predicate; } protected override bool ShouldCheckTypeForMembers(MergedTypeDeclaration current) { // Note: this preserves the behavior the compiler has always had when a predicate // is passed in. We could potentially be smarter by checking the predicate // against the list of member names in the type declaration first. return true; } protected override bool Matches(string name) => _predicate(name); } private class NameSymbolSearcher : AbstractSymbolSearcher { private readonly string _name; public NameSymbolSearcher( CSharpCompilation compilation, SymbolFilter filter, string name, CancellationToken cancellationToken) : base(compilation, filter, cancellationToken) { _name = name; } protected override bool ShouldCheckTypeForMembers(MergedTypeDeclaration current) { foreach (SingleTypeDeclaration typeDecl in current.Declarations) { if (typeDecl.MemberNames.ContainsKey(_name)) { return true; } } return false; } protected override bool Matches(string name) => _name == name; } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Threading; using Microsoft.Cci; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.Binder; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The compilation object is an immutable representation of a single invocation of the /// compiler. Although immutable, a compilation is also on-demand, and will realize and cache /// data as necessary. A compilation can produce a new compilation from existing compilation /// with the application of small deltas. In many cases, it is more efficient than creating a /// new compilation from scratch, as the new compilation can reuse information from the old /// compilation. /// </summary> public sealed partial class CSharpCompilation : Compilation { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // // 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. // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! private readonly CSharpCompilationOptions _options; private readonly Lazy<UsingsFromOptionsAndDiagnostics> _usingsFromOptions; private readonly Lazy<ImmutableArray<NamespaceOrTypeAndUsingDirective>> _globalImports; private readonly Lazy<Imports> _previousSubmissionImports; private readonly Lazy<AliasSymbol> _globalNamespaceAlias; // alias symbol used to resolve "global::". private readonly Lazy<ImplicitNamedTypeSymbol?> _scriptClass; // The type of host object model if available. private TypeSymbol? _lazyHostObjectTypeSymbol; /// <summary> /// All imports (using directives and extern aliases) in syntax trees in this compilation. /// NOTE: We need to de-dup since the Imports objects that populate the list may be GC'd /// and re-created. /// Values are the sets of dependencies for corresponding directives. /// </summary> private ConcurrentDictionary<ImportInfo, ImmutableArray<AssemblySymbol>>? _lazyImportInfos; // Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly. // NOTE: Presently, we do not cache the per-tree diagnostics. private ImmutableArray<Diagnostic> _lazyClsComplianceDiagnostics; private ImmutableArray<AssemblySymbol> _lazyClsComplianceDependencies; private Conversions? _conversions; /// <summary> /// A conversions object that ignores nullability. /// </summary> internal Conversions Conversions { get { if (_conversions == null) { Interlocked.CompareExchange(ref _conversions, new BuckStopsHereBinder(this).Conversions, null); } return _conversions; } } /// <summary> /// Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent. /// </summary> private readonly AnonymousTypeManager _anonymousTypeManager; private NamespaceSymbol? _lazyGlobalNamespace; internal readonly BuiltInOperators builtInOperators; /// <summary> /// The <see cref="SourceAssemblySymbol"/> for this compilation. Do not access directly, use Assembly property /// instead. This field is lazily initialized by ReferenceManager, ReferenceManager.CacheLockObject must be locked /// while ReferenceManager "calculates" the value and assigns it, several threads must not perform duplicate /// "calculation" simultaneously. /// </summary> private SourceAssemblySymbol? _lazyAssemblySymbol; /// <summary> /// Holds onto data related to reference binding. /// The manager is shared among multiple compilations that we expect to have the same result of reference binding. /// In most cases this can be determined without performing the binding. If the compilation however contains a circular /// metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results. /// We do so by creating a new reference manager for such compilation. /// </summary> private ReferenceManager _referenceManager; private readonly SyntaxAndDeclarationManager _syntaxAndDeclarations; /// <summary> /// Contains the main method of this assembly, if there is one. /// </summary> private EntryPoint? _lazyEntryPoint; /// <summary> /// Emit nullable attributes for only those members that are visible outside the assembly /// (public, protected, and if any [InternalsVisibleTo] attributes, internal members). /// If false, attributes are emitted for all members regardless of visibility. /// </summary> private ThreeState _lazyEmitNullablePublicOnly; /// <summary> /// The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue. /// </summary> private HashSet<SyntaxTree>? _lazyCompilationUnitCompletedTrees; /// <summary> /// The set of trees for which enough analysis was performed in order to record usage of using directives. /// Once all trees are processed the value is set to null. /// </summary> private ImmutableHashSet<SyntaxTree>? _usageOfUsingsRecordedInTrees = ImmutableHashSet<SyntaxTree>.Empty; /// <summary> /// Nullable analysis data for methods, parameter default values, and attributes. /// The key is a symbol for methods or parameters, and syntax for attributes. /// The data is collected during testing only. /// </summary> internal NullableData? NullableAnalysisData; internal sealed class NullableData { internal readonly int MaxRecursionDepth; internal readonly ConcurrentDictionary<object, NullableWalker.Data> Data; internal NullableData(int maxRecursionDepth = -1) { MaxRecursionDepth = maxRecursionDepth; Data = new ConcurrentDictionary<object, NullableWalker.Data>(); } } internal ImmutableHashSet<SyntaxTree>? UsageOfUsingsRecordedInTrees => Volatile.Read(ref _usageOfUsingsRecordedInTrees); public override string Language { get { return LanguageNames.CSharp; } } public override bool IsCaseSensitive { get { return true; } } /// <summary> /// The options the compilation was created with. /// </summary> public new CSharpCompilationOptions Options { get { return _options; } } internal AnonymousTypeManager AnonymousTypeManager { get { return _anonymousTypeManager; } } internal override CommonAnonymousTypeManager CommonAnonymousTypeManager { get { return AnonymousTypeManager; } } /// <summary> /// True when the compiler is run in "strict" mode, in which it enforces the language specification /// in some cases even at the expense of full compatibility. Such differences typically arise when /// earlier versions of the compiler failed to enforce the full language specification. /// </summary> internal bool FeatureStrictEnabled => Feature("strict") != null; /// <summary> /// True when the "peverify-compat" feature flag is set or the language version is below C# 7.2. /// With this flag we will avoid certain patterns known not be compatible with PEVerify. /// The code may be less efficient and may deviate from spec in corner cases. /// The flag is only to be used if PEVerify pass is extremely important. /// </summary> internal bool IsPeVerifyCompatEnabled => LanguageVersion < LanguageVersion.CSharp7_2 || Feature("peverify-compat") != null; /// <summary> /// Returns true if nullable analysis is enabled in the text span represented by the syntax node. /// </summary> /// <remarks> /// This overload is used for member symbols during binding, or for cases other /// than symbols such as attribute arguments and parameter defaults. /// </remarks> internal bool IsNullableAnalysisEnabledIn(SyntaxNode syntax) { return IsNullableAnalysisEnabledIn((CSharpSyntaxTree)syntax.SyntaxTree, syntax.Span); } /// <summary> /// Returns true if nullable analysis is enabled in the text span. /// </summary> /// <remarks> /// This overload is used for member symbols during binding, or for cases other /// than symbols such as attribute arguments and parameter defaults. /// </remarks> internal bool IsNullableAnalysisEnabledIn(CSharpSyntaxTree tree, TextSpan span) { return GetNullableAnalysisValue() ?? tree.IsNullableAnalysisEnabled(span) ?? (Options.NullableContextOptions & NullableContextOptions.Warnings) != 0; } /// <summary> /// Returns true if nullable analysis is enabled for the method. For constructors, the /// region considered may include other constructors and field and property initializers. /// </summary> /// <remarks> /// This overload is intended for callers that rely on symbols rather than syntax. The overload /// uses the cached value calculated during binding (from potentially several spans) /// from <see cref="IsNullableAnalysisEnabledIn(CSharpSyntaxTree, TextSpan)"/>. /// </remarks> internal bool IsNullableAnalysisEnabledIn(MethodSymbol method) { return GetNullableAnalysisValue() ?? method.IsNullableAnalysisEnabled(); } /// <summary> /// Returns true if nullable analysis is enabled for all methods regardless /// of the actual nullable context. /// If this property returns true but IsNullableAnalysisEnabled returns false, /// any nullable analysis should be enabled but results should be ignored. /// </summary> /// <remarks> /// For DEBUG builds, we treat nullable analysis as enabled for all methods /// unless explicitly disabled, so that analysis is run, even though results may /// be ignored, to increase the chance of catching nullable regressions /// (e.g. https://github.com/dotnet/roslyn/issues/40136). /// </remarks> internal bool IsNullableAnalysisEnabledAlways { get { var value = GetNullableAnalysisValue(); #if DEBUG return value != false; #else return value == true; #endif } } /// <summary> /// Returns Feature("run-nullable-analysis") as a bool? value: /// true for "always"; false for "never"; and null otherwise. /// </summary> private bool? GetNullableAnalysisValue() { return Feature("run-nullable-analysis") switch { "always" => true, "never" => false, _ => null, }; } /// <summary> /// The language version that was used to parse the syntax trees of this compilation. /// </summary> public LanguageVersion LanguageVersion { get; } protected override INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity) { return new ExtendedErrorTypeSymbol( container.EnsureCSharpSymbolOrNull(nameof(container)), name, arity, errorInfo: null).GetPublicSymbol(); } protected override INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name) { return new MissingNamespaceSymbol( container.EnsureCSharpSymbolOrNull(nameof(container)), name).GetPublicSymbol(); } #region Constructors and Factories private static readonly CSharpCompilationOptions s_defaultOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication); private static readonly CSharpCompilationOptions s_defaultSubmissionOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithReferencesSupersedeLowerVersions(true); /// <summary> /// Creates a new compilation from scratch. Methods such as AddSyntaxTrees or AddReferences /// on the returned object will allow to continue building up the Compilation incrementally. /// </summary> /// <param name="assemblyName">Simple assembly name.</param> /// <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param> /// <param name="references">The references for the new compilation.</param> /// <param name="options">The compiler options to use.</param> /// <returns>A new compilation.</returns> public static CSharpCompilation Create( string? assemblyName, IEnumerable<SyntaxTree>? syntaxTrees = null, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null) { return Create( assemblyName, options ?? s_defaultOptions, syntaxTrees, references, previousSubmission: null, returnType: null, hostObjectType: null, isSubmission: false); } /// <summary> /// Creates a new compilation that can be used in scripting. /// </summary> public static CSharpCompilation CreateScriptCompilation( string assemblyName, SyntaxTree? syntaxTree = null, IEnumerable<MetadataReference>? references = null, CSharpCompilationOptions? options = null, CSharpCompilation? previousScriptCompilation = null, Type? returnType = null, Type? globalsType = null) { CheckSubmissionOptions(options); ValidateScriptCompilationParameters(previousScriptCompilation, returnType, ref globalsType); return Create( assemblyName, options?.WithReferencesSupersedeLowerVersions(true) ?? s_defaultSubmissionOptions, (syntaxTree != null) ? new[] { syntaxTree } : SpecializedCollections.EmptyEnumerable<SyntaxTree>(), references, previousScriptCompilation, returnType, globalsType, isSubmission: true); } private static CSharpCompilation Create( string? assemblyName, CSharpCompilationOptions options, IEnumerable<SyntaxTree>? syntaxTrees, IEnumerable<MetadataReference>? references, CSharpCompilation? previousSubmission, Type? returnType, Type? hostObjectType, bool isSubmission) { RoslynDebug.Assert(options != null); Debug.Assert(!isSubmission || options.ReferencesSupersedeLowerVersions); var validatedReferences = ValidateReferences<CSharpCompilationReference>(references); // We can't reuse the whole Reference Manager entirely (reuseReferenceManager = false) // because the set of references of this submission differs from the previous one. // The submission inherits references of the previous submission, adds the previous submission reference // and may add more references passed explicitly or via #r. // // TODO: Consider reusing some results of the assembly binding to improve perf // since most of the binding work is similar. // https://github.com/dotnet/roslyn/issues/43397 var compilation = new CSharpCompilation( assemblyName, options, validatedReferences, previousSubmission, returnType, hostObjectType, isSubmission, referenceManager: null, reuseReferenceManager: false, syntaxAndDeclarations: new SyntaxAndDeclarationManager( ImmutableArray<SyntaxTree>.Empty, options.ScriptClassName, options.SourceReferenceResolver, CSharp.MessageProvider.Instance, isSubmission, state: null), semanticModelProvider: null); if (syntaxTrees != null) { compilation = compilation.AddSyntaxTrees(syntaxTrees); } Debug.Assert(compilation._lazyAssemblySymbol is null); return compilation; } private CSharpCompilation( string? assemblyName, CSharpCompilationOptions options, ImmutableArray<MetadataReference> references, CSharpCompilation? previousSubmission, Type? submissionReturnType, Type? hostObjectType, bool isSubmission, ReferenceManager? referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations, SemanticModelProvider? semanticModelProvider, AsyncQueue<CompilationEvent>? eventQueue = null) : this(assemblyName, options, references, previousSubmission, submissionReturnType, hostObjectType, isSubmission, referenceManager, reuseReferenceManager, syntaxAndDeclarations, SyntaxTreeCommonFeatures(syntaxAndDeclarations.ExternalSyntaxTrees), semanticModelProvider, eventQueue) { } private CSharpCompilation( string? assemblyName, CSharpCompilationOptions options, ImmutableArray<MetadataReference> references, CSharpCompilation? previousSubmission, Type? submissionReturnType, Type? hostObjectType, bool isSubmission, ReferenceManager? referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations, IReadOnlyDictionary<string, string> features, SemanticModelProvider? semanticModelProvider, AsyncQueue<CompilationEvent>? eventQueue = null) : base(assemblyName, references, features, isSubmission, semanticModelProvider, eventQueue) { WellKnownMemberSignatureComparer = new WellKnownMembersSignatureComparer(this); _options = options; this.builtInOperators = new BuiltInOperators(this); _scriptClass = new Lazy<ImplicitNamedTypeSymbol?>(BindScriptClass); _globalImports = new Lazy<ImmutableArray<NamespaceOrTypeAndUsingDirective>>(BindGlobalImports); _usingsFromOptions = new Lazy<UsingsFromOptionsAndDiagnostics>(BindUsingsFromOptions); _previousSubmissionImports = new Lazy<Imports>(ExpandPreviousSubmissionImports); _globalNamespaceAlias = new Lazy<AliasSymbol>(CreateGlobalNamespaceAlias); _anonymousTypeManager = new AnonymousTypeManager(this); this.LanguageVersion = CommonLanguageVersion(syntaxAndDeclarations.ExternalSyntaxTrees); if (isSubmission) { Debug.Assert(previousSubmission == null || previousSubmission.HostObjectType == hostObjectType); this.ScriptCompilationInfo = new CSharpScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType); } else { Debug.Assert(previousSubmission == null && submissionReturnType == null && hostObjectType == null); } if (reuseReferenceManager) { if (referenceManager is null) { throw new ArgumentNullException(nameof(referenceManager)); } referenceManager.AssertCanReuseForCompilation(this); _referenceManager = referenceManager; } else { _referenceManager = new ReferenceManager( MakeSourceAssemblySimpleName(), this.Options.AssemblyIdentityComparer, observedMetadata: referenceManager?.ObservedMetadata); } _syntaxAndDeclarations = syntaxAndDeclarations; Debug.Assert(_lazyAssemblySymbol is null); if (EventQueue != null) EventQueue.TryEnqueue(new CompilationStartedEvent(this)); } internal override void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics) { Debug.Assert(debugEntryPoint != null); // Debug entry point has to be a method definition from this compilation. var methodSymbol = (debugEntryPoint as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol; if (methodSymbol?.DeclaringCompilation != this || !methodSymbol.IsDefinition) { diagnostics.Add(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None); } } private static LanguageVersion CommonLanguageVersion(ImmutableArray<SyntaxTree> syntaxTrees) { LanguageVersion? result = null; foreach (var tree in syntaxTrees) { var version = ((CSharpParseOptions)tree.Options).LanguageVersion; if (result == null) { result = version; } else if (result != version) { throw new ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, nameof(syntaxTrees)); } } return result ?? LanguageVersion.Default.MapSpecifiedToEffectiveVersion(); } /// <summary> /// Create a duplicate of this compilation with different symbol instances. /// </summary> public new CSharpCompilation Clone() { return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, this.SemanticModelProvider); } private CSharpCompilation Update( ReferenceManager referenceManager, bool reuseReferenceManager, SyntaxAndDeclarationManager syntaxAndDeclarations) { return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, referenceManager, reuseReferenceManager, syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Creates a new compilation with the specified name. /// </summary> public new CSharpCompilation WithAssemblyName(string? assemblyName) { // Can't reuse references since the source assembly name changed and the referenced symbols might // have internals-visible-to relationship with this compilation or they might had a circular reference // to this compilation. return new CSharpCompilation( assemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: assemblyName == this.AssemblyName, _syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> /// <remarks> /// The new <see cref="CSharpCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying /// metadata as soon as the are needed. /// /// The new compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>. /// E.g. if the current compilation references a metadata file that has changed since the creation of the compilation /// the new compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change). /// </remarks> public new CSharpCompilation WithReferences(IEnumerable<MetadataReference>? references) { // References might have changed, don't reuse reference manager. // Don't even reuse observed metadata - let the manager query for the metadata again. return new CSharpCompilation( this.AssemblyName, _options, ValidateReferences<CSharpCompilationReference>(references), this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, referenceManager: null, reuseReferenceManager: false, _syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> public new CSharpCompilation WithReferences(params MetadataReference[] references) { return this.WithReferences((IEnumerable<MetadataReference>)references); } /// <summary> /// Creates a new compilation with the specified compilation options. /// </summary> public CSharpCompilation WithOptions(CSharpCompilationOptions options) { var oldOptions = this.Options; bool reuseReferenceManager = oldOptions.CanReuseCompilationReferenceManager(options); bool reuseSyntaxAndDeclarationManager = oldOptions.ScriptClassName == options.ScriptClassName && oldOptions.SourceReferenceResolver == options.SourceReferenceResolver; return new CSharpCompilation( this.AssemblyName, options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager, reuseSyntaxAndDeclarationManager ? _syntaxAndDeclarations : new SyntaxAndDeclarationManager( _syntaxAndDeclarations.ExternalSyntaxTrees, options.ScriptClassName, options.SourceReferenceResolver, _syntaxAndDeclarations.MessageProvider, _syntaxAndDeclarations.IsSubmission, state: null), this.SemanticModelProvider); } /// <summary> /// Returns a new compilation with the given compilation set as the previous submission. /// </summary> public CSharpCompilation WithScriptCompilationInfo(CSharpScriptCompilationInfo? info) { if (info == ScriptCompilationInfo) { return this; } // Metadata references are inherited from the previous submission, // so we can only reuse the manager if we can guarantee that these references are the same. // Check if the previous script compilation doesn't change. // TODO: Consider comparing the metadata references if they have been bound already. // https://github.com/dotnet/roslyn/issues/43397 bool reuseReferenceManager = ReferenceEquals(ScriptCompilationInfo?.PreviousScriptCompilation, info?.PreviousScriptCompilation); return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, info?.PreviousScriptCompilation, info?.ReturnTypeOpt, info?.GlobalsType, isSubmission: info != null, _referenceManager, reuseReferenceManager, _syntaxAndDeclarations, this.SemanticModelProvider); } /// <summary> /// Returns a new compilation with the given semantic model provider. /// </summary> internal override Compilation WithSemanticModelProvider(SemanticModelProvider? semanticModelProvider) { if (this.SemanticModelProvider == semanticModelProvider) { return this; } return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, semanticModelProvider); } /// <summary> /// Returns a new compilation with a given event queue. /// </summary> internal override Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue) { return new CSharpCompilation( this.AssemblyName, _options, this.ExternalReferences, this.PreviousSubmission, this.SubmissionReturnType, this.HostObjectType, this.IsSubmission, _referenceManager, reuseReferenceManager: true, _syntaxAndDeclarations, this.SemanticModelProvider, eventQueue); } #endregion #region Submission public new CSharpScriptCompilationInfo? ScriptCompilationInfo { get; } internal override ScriptCompilationInfo? CommonScriptCompilationInfo => ScriptCompilationInfo; internal CSharpCompilation? PreviousSubmission => ScriptCompilationInfo?.PreviousScriptCompilation; internal override bool HasSubmissionResult() { Debug.Assert(IsSubmission); // A submission may be empty or comprised of a single script file. var tree = _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault(); if (tree == null) { return false; } var root = tree.GetCompilationUnitRoot(); if (root.HasErrors) { return false; } // Are there any top-level return statements? if (root.DescendantNodes(n => n is GlobalStatementSyntax || n is StatementSyntax || n is CompilationUnitSyntax).Any(n => n.IsKind(SyntaxKind.ReturnStatement))) { return true; } // Is there a trailing expression? var lastGlobalStatement = (GlobalStatementSyntax?)root.Members.LastOrDefault(m => m.IsKind(SyntaxKind.GlobalStatement)); if (lastGlobalStatement != null) { var statement = lastGlobalStatement.Statement; if (statement.IsKind(SyntaxKind.ExpressionStatement)) { var expressionStatement = (ExpressionStatementSyntax)statement; if (expressionStatement.SemicolonToken.IsMissing) { var model = GetSemanticModel(tree); var expression = expressionStatement.Expression; var info = model.GetTypeInfo(expression); return info.ConvertedType?.SpecialType != SpecialType.System_Void; } } } return false; } #endregion #region Syntax Trees (maintain an ordered list) /// <summary> /// The syntax trees (parsed from source code) that this compilation was created with. /// </summary> public new ImmutableArray<SyntaxTree> SyntaxTrees { get { return _syntaxAndDeclarations.GetLazyState().SyntaxTrees; } } /// <summary> /// Returns true if this compilation contains the specified tree. False otherwise. /// </summary> public new bool ContainsSyntaxTree(SyntaxTree? syntaxTree) { return syntaxTree != null && _syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree); } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> public new CSharpCompilation AddSyntaxTrees(params SyntaxTree[] trees) { return AddSyntaxTrees((IEnumerable<SyntaxTree>)trees); } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> public new CSharpCompilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees) { if (trees == null) { throw new ArgumentNullException(nameof(trees)); } if (trees.IsEmpty()) { return this; } // This HashSet is needed so that we don't allow adding the same tree twice // with a single call to AddSyntaxTrees. Rather than using a separate HashSet, // ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we // only allow replacing a single tree at a time. var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance(); var syntaxAndDeclarations = _syntaxAndDeclarations; externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees); bool reuseReferenceManager = true; int i = 0; foreach (var tree in trees.Cast<CSharpSyntaxTree>()) { if (tree == null) { throw new ArgumentNullException($"{nameof(trees)}[{i}]"); } if (!tree.HasCompilationUnitRoot) { throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, $"{nameof(trees)}[{i}]"); } if (externalSyntaxTrees.Contains(tree)) { throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, $"{nameof(trees)}[{i}]"); } if (this.IsSubmission && tree.Options.Kind == SourceCodeKind.Regular) { throw new ArgumentException(CSharpResources.SubmissionCanOnlyInclude, $"{nameof(trees)}[{i}]"); } externalSyntaxTrees.Add(tree); reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives; i++; } externalSyntaxTrees.Free(); if (this.IsSubmission && i > 1) { throw new ArgumentException(CSharpResources.SubmissionCanHaveAtMostOne, nameof(trees)); } syntaxAndDeclarations = syntaxAndDeclarations.AddSyntaxTrees(trees); return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations); } /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> public new CSharpCompilation RemoveSyntaxTrees(params SyntaxTree[] trees) { return RemoveSyntaxTrees((IEnumerable<SyntaxTree>)trees); } /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees) { if (trees == null) { throw new ArgumentNullException(nameof(trees)); } if (trees.IsEmpty()) { return this; } var removeSet = PooledHashSet<SyntaxTree>.GetInstance(); // This HashSet is needed so that we don't allow adding the same tree twice // with a single call to AddSyntaxTrees. Rather than using a separate HashSet, // ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we // only allow replacing a single tree at a time. var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance(); var syntaxAndDeclarations = _syntaxAndDeclarations; externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees); bool reuseReferenceManager = true; int i = 0; foreach (var tree in trees.Cast<CSharpSyntaxTree>()) { if (!externalSyntaxTrees.Contains(tree)) { // Check to make sure this is not a #load'ed tree. var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap; if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(tree, loadedSyntaxTreeMap)) { throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, $"{nameof(trees)}[{i}]"); } throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, $"{nameof(trees)}[{i}]"); } removeSet.Add(tree); reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives; i++; } externalSyntaxTrees.Free(); syntaxAndDeclarations = syntaxAndDeclarations.RemoveSyntaxTrees(removeSet); removeSet.Free(); return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations); } /// <summary> /// Creates a new compilation without any syntax trees. Preserves metadata info /// from this compilation for use with trees added later. /// </summary> public new CSharpCompilation RemoveAllSyntaxTrees() { var syntaxAndDeclarations = _syntaxAndDeclarations; return Update( _referenceManager, reuseReferenceManager: !syntaxAndDeclarations.MayHaveReferenceDirectives(), syntaxAndDeclarations: syntaxAndDeclarations.WithExternalSyntaxTrees(ImmutableArray<SyntaxTree>.Empty)); } /// <summary> /// Creates a new compilation without the old tree but with the new tree. /// </summary> public new CSharpCompilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree? newTree) { // this is just to force a cast exception oldTree = (CSharpSyntaxTree)oldTree; newTree = (CSharpSyntaxTree?)newTree; if (oldTree == null) { throw new ArgumentNullException(nameof(oldTree)); } if (newTree == null) { return this.RemoveSyntaxTrees(oldTree); } else if (newTree == oldTree) { return this; } if (!newTree.HasCompilationUnitRoot) { throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, nameof(newTree)); } var syntaxAndDeclarations = _syntaxAndDeclarations; var externalSyntaxTrees = syntaxAndDeclarations.ExternalSyntaxTrees; if (!externalSyntaxTrees.Contains(oldTree)) { // Check to see if this is a #load'ed tree. var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap; if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(oldTree, loadedSyntaxTreeMap)) { throw new ArgumentException(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, nameof(oldTree)); } throw new ArgumentException(CSharpResources.SyntaxTreeNotFoundToRemove, nameof(oldTree)); } if (externalSyntaxTrees.Contains(newTree)) { throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, nameof(newTree)); } // TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse. // This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke // that replaces the tree with a new one. // https://github.com/dotnet/roslyn/issues/43397 var reuseReferenceManager = !oldTree.HasReferenceOrLoadDirectives() && !newTree.HasReferenceOrLoadDirectives(); syntaxAndDeclarations = syntaxAndDeclarations.ReplaceSyntaxTree(oldTree, newTree); return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations); } internal override int GetSyntaxTreeOrdinal(SyntaxTree tree) { Debug.Assert(this.ContainsSyntaxTree(tree)); return _syntaxAndDeclarations.GetLazyState().OrdinalMap[tree]; } #endregion #region References internal override CommonReferenceManager CommonGetBoundReferenceManager() { return GetBoundReferenceManager(); } internal new ReferenceManager GetBoundReferenceManager() { if (_lazyAssemblySymbol is null) { _referenceManager.CreateSourceAssemblyForCompilation(this); Debug.Assert(_lazyAssemblySymbol is object); } // referenceManager can only be accessed after we initialized the lazyAssemblySymbol. // In fact, initialization of the assembly symbol might change the reference manager. return _referenceManager; } // for testing only: internal bool ReferenceManagerEquals(CSharpCompilation other) { return ReferenceEquals(_referenceManager, other._referenceManager); } public override ImmutableArray<MetadataReference> DirectiveReferences { get { return GetBoundReferenceManager().DirectiveReferences; } } internal override IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap => GetBoundReferenceManager().ReferenceDirectiveMap; // for testing purposes internal IEnumerable<string> ExternAliases { get { return GetBoundReferenceManager().ExternAliases; } } /// <summary> /// Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation. /// </summary> /// <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or null if there is none.</returns> /// <remarks> /// Uses object identity when comparing two references. /// </remarks> internal new Symbol? GetAssemblyOrModuleSymbol(MetadataReference reference) { if (reference == null) { throw new ArgumentNullException(nameof(reference)); } if (reference.Properties.Kind == MetadataImageKind.Assembly) { return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference); } else { Debug.Assert(reference.Properties.Kind == MetadataImageKind.Module); int index = GetBoundReferenceManager().GetReferencedModuleIndex(reference); return index < 0 ? null : this.Assembly.Modules[index]; } } public override IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get { return Assembly.Modules.SelectMany(module => module.GetReferencedAssemblies()); } } /// <summary> /// All reference directives used in this compilation. /// </summary> internal override IEnumerable<ReferenceDirective> ReferenceDirectives { get { return this.Declarations.ReferenceDirectives; } } /// <summary> /// Returns a metadata reference that a given #r resolves to. /// </summary> /// <param name="directive">#r directive.</param> /// <returns>Metadata reference the specified directive resolves to, or null if the <paramref name="directive"/> doesn't match any #r directive in the compilation.</returns> public MetadataReference? GetDirectiveReference(ReferenceDirectiveTriviaSyntax directive) { RoslynDebug.Assert(directive.SyntaxTree.FilePath is object); MetadataReference? reference; return ReferenceDirectiveMap.TryGetValue((directive.SyntaxTree.FilePath, directive.File.ValueText), out reference) ? reference : null; } /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> public new CSharpCompilation AddReferences(params MetadataReference[] references) { return (CSharpCompilation)base.AddReferences(references); } /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> public new CSharpCompilation AddReferences(IEnumerable<MetadataReference> references) { return (CSharpCompilation)base.AddReferences(references); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> public new CSharpCompilation RemoveReferences(params MetadataReference[] references) { return (CSharpCompilation)base.RemoveReferences(references); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> public new CSharpCompilation RemoveReferences(IEnumerable<MetadataReference> references) { return (CSharpCompilation)base.RemoveReferences(references); } /// <summary> /// Creates a new compilation without any metadata references /// </summary> public new CSharpCompilation RemoveAllReferences() { return (CSharpCompilation)base.RemoveAllReferences(); } /// <summary> /// Creates a new compilation with an old metadata reference replaced with a new metadata reference. /// </summary> public new CSharpCompilation ReplaceReference(MetadataReference oldReference, MetadataReference newReference) { return (CSharpCompilation)base.ReplaceReference(oldReference, newReference); } public override CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default, bool embedInteropTypes = false) { return new CSharpCompilationReference(this, aliases, embedInteropTypes); } /// <summary> /// Get all modules in this compilation, including the source module, added modules, and all /// modules of referenced assemblies that do not come from an assembly with an extern alias. /// Metadata imported from aliased assemblies is not visible at the source level except through /// the use of an extern alias directive. So exclude them from this list which is used to construct /// the global namespace. /// </summary> private void GetAllUnaliasedModules(ArrayBuilder<ModuleSymbol> modules) { // NOTE: This includes referenced modules - they count as modules of the compilation assembly. modules.AddRange(Assembly.Modules); var referenceManager = GetBoundReferenceManager(); for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++) { if (referenceManager.DeclarationsAccessibleWithoutAlias(i)) { modules.AddRange(referenceManager.ReferencedAssemblies[i].Modules); } } } /// <summary> /// Return a list of assembly symbols than can be accessed without using an alias. /// For example: /// 1) /r:A.dll /r:B.dll -> A, B /// 2) /r:Goo=A.dll /r:B.dll -> B /// 3) /r:Goo=A.dll /r:A.dll -> A /// </summary> internal void GetUnaliasedReferencedAssemblies(ArrayBuilder<AssemblySymbol> assemblies) { var referenceManager = GetBoundReferenceManager(); for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++) { if (referenceManager.DeclarationsAccessibleWithoutAlias(i)) { assemblies.Add(referenceManager.ReferencedAssemblies[i]); } } } /// <summary> /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. /// </summary> public new MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol) { return base.GetMetadataReference(assemblySymbol); } private protected override MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol) { if (assemblySymbol is Symbols.PublicModel.AssemblySymbol { UnderlyingAssemblySymbol: var underlyingSymbol }) { return GetMetadataReference(underlyingSymbol); } return null; } internal MetadataReference? GetMetadataReference(AssemblySymbol? assemblySymbol) { return GetBoundReferenceManager().GetMetadataReference(assemblySymbol); } #endregion #region Symbols /// <summary> /// The AssemblySymbol that represents the assembly being created. /// </summary> internal SourceAssemblySymbol SourceAssembly { get { GetBoundReferenceManager(); RoslynDebug.Assert(_lazyAssemblySymbol is object); return _lazyAssemblySymbol; } } /// <summary> /// The AssemblySymbol that represents the assembly being created. /// </summary> internal new AssemblySymbol Assembly { get { return SourceAssembly; } } /// <summary> /// Get a ModuleSymbol that refers to the module being created by compiling all of the code. /// By getting the GlobalNamespace property of that module, all of the namespaces and types /// defined in source code can be obtained. /// </summary> internal new ModuleSymbol SourceModule { get { return Assembly.Modules[0]; } } /// <summary> /// Gets the root namespace that contains all namespaces and types defined in source code or in /// referenced metadata, merged into a single namespace hierarchy. /// </summary> internal new NamespaceSymbol GlobalNamespace { get { if (_lazyGlobalNamespace is null) { // Get the root namespace from each module, and merge them all together // Get all modules in this compilation, ones referenced directly by the compilation // as well as those referenced by all referenced assemblies. var modules = ArrayBuilder<ModuleSymbol>.GetInstance(); GetAllUnaliasedModules(modules); var result = MergedNamespaceSymbol.Create( new NamespaceExtent(this), null, modules.SelectDistinct(m => m.GlobalNamespace)); modules.Free(); Interlocked.CompareExchange(ref _lazyGlobalNamespace, result, null); } return _lazyGlobalNamespace; } } /// <summary> /// Given for the specified module or assembly namespace, gets the corresponding compilation /// namespace (merged namespace representation for all namespace declarations and references /// with contributions for the namespaceSymbol). Can return null if no corresponding /// namespace can be bound in this compilation with the same name. /// </summary> internal new NamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol) { if (namespaceSymbol is Symbols.PublicModel.NamespaceSymbol n && namespaceSymbol.NamespaceKind == NamespaceKind.Compilation && namespaceSymbol.ContainingCompilation == this) { return n.UnderlyingNamespaceSymbol; } var containingNamespace = namespaceSymbol.ContainingNamespace; if (containingNamespace == null) { return this.GlobalNamespace; } var current = GetCompilationNamespace(containingNamespace); if (current is object) { return current.GetNestedNamespace(namespaceSymbol.Name); } return null; } internal NamespaceSymbol? GetCompilationNamespace(NamespaceSymbol namespaceSymbol) { if (namespaceSymbol.NamespaceKind == NamespaceKind.Compilation && namespaceSymbol.ContainingCompilation == this) { return namespaceSymbol; } var containingNamespace = namespaceSymbol.ContainingNamespace; if (containingNamespace == null) { return this.GlobalNamespace; } var current = GetCompilationNamespace(containingNamespace); if (current is object) { return current.GetNestedNamespace(namespaceSymbol.Name); } return null; } private ConcurrentDictionary<string, NamespaceSymbol>? _externAliasTargets; internal bool GetExternAliasTarget(string aliasName, out NamespaceSymbol @namespace) { if (_externAliasTargets == null) { Interlocked.CompareExchange(ref _externAliasTargets, new ConcurrentDictionary<string, NamespaceSymbol>(), null); } else if (_externAliasTargets.TryGetValue(aliasName, out var cached)) { @namespace = cached; return !(@namespace is MissingNamespaceSymbol); } ArrayBuilder<NamespaceSymbol>? builder = null; var referenceManager = GetBoundReferenceManager(); for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++) { if (referenceManager.AliasesOfReferencedAssemblies[i].Contains(aliasName)) { builder = builder ?? ArrayBuilder<NamespaceSymbol>.GetInstance(); builder.Add(referenceManager.ReferencedAssemblies[i].GlobalNamespace); } } bool foundNamespace = builder != null; // We want to cache failures as well as successes so that subsequent incorrect extern aliases with the // same alias will have the same target. @namespace = foundNamespace ? MergedNamespaceSymbol.Create(new NamespaceExtent(this), namespacesToMerge: builder!.ToImmutableAndFree(), containingNamespace: null, nameOpt: null) : new MissingNamespaceSymbol(new MissingModuleSymbol(new MissingAssemblySymbol(new AssemblyIdentity(System.Guid.NewGuid().ToString())), ordinal: -1)); // Use GetOrAdd in case another thread beat us to the punch (i.e. should return the same object for the same alias, every time). @namespace = _externAliasTargets.GetOrAdd(aliasName, @namespace); Debug.Assert(foundNamespace == !(@namespace is MissingNamespaceSymbol)); return foundNamespace; } /// <summary> /// A symbol representing the implicit Script class. This is null if the class is not /// defined in the compilation. /// </summary> internal new NamedTypeSymbol? ScriptClass { get { return _scriptClass.Value; } } /// <summary> /// Resolves a symbol that represents script container (Script class). Uses the /// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol. /// </summary> /// <returns>The Script class symbol or null if it is not defined.</returns> private ImplicitNamedTypeSymbol? BindScriptClass() { return (ImplicitNamedTypeSymbol?)CommonBindScriptClass().GetSymbol(); } internal bool IsSubmissionSyntaxTree(SyntaxTree tree) { Debug.Assert(tree != null); Debug.Assert(!this.IsSubmission || _syntaxAndDeclarations.ExternalSyntaxTrees.Length <= 1); return this.IsSubmission && tree == _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault(); } /// <summary> /// Global imports (including those from previous submissions, if there are any). /// </summary> internal ImmutableArray<NamespaceOrTypeAndUsingDirective> GlobalImports => _globalImports.Value; private ImmutableArray<NamespaceOrTypeAndUsingDirective> BindGlobalImports() { var usingsFromoptions = UsingsFromOptions; var previousSubmission = PreviousSubmission; var previousSubmissionImports = previousSubmission is object ? Imports.ExpandPreviousSubmissionImports(previousSubmission.GlobalImports, this) : ImmutableArray<NamespaceOrTypeAndUsingDirective>.Empty; if (usingsFromoptions.UsingNamespacesOrTypes.IsEmpty) { return previousSubmissionImports; } else if (previousSubmissionImports.IsEmpty) { return usingsFromoptions.UsingNamespacesOrTypes; } var boundUsings = ArrayBuilder<NamespaceOrTypeAndUsingDirective>.GetInstance(); var uniqueUsings = PooledHashSet<NamespaceOrTypeSymbol>.GetInstance(); boundUsings.AddRange(usingsFromoptions.UsingNamespacesOrTypes); uniqueUsings.AddAll(usingsFromoptions.UsingNamespacesOrTypes.Select(static unt => unt.NamespaceOrType)); foreach (var previousUsing in previousSubmissionImports) { if (uniqueUsings.Add(previousUsing.NamespaceOrType)) { boundUsings.Add(previousUsing); } } uniqueUsings.Free(); return boundUsings.ToImmutableAndFree(); } /// <summary> /// Global imports not including those from previous submissions. /// </summary> private UsingsFromOptionsAndDiagnostics UsingsFromOptions => _usingsFromOptions.Value; private UsingsFromOptionsAndDiagnostics BindUsingsFromOptions() => UsingsFromOptionsAndDiagnostics.FromOptions(this); /// <summary> /// Imports declared by this submission (null if this isn't one). /// </summary> internal Imports GetSubmissionImports() { Debug.Assert(this.IsSubmission); Debug.Assert(_syntaxAndDeclarations.ExternalSyntaxTrees.Length <= 1); // A submission may be empty or comprised of a single script file. var tree = _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault(); if (tree == null) { return Imports.Empty; } return ((SourceNamespaceSymbol)SourceModule.GlobalNamespace).GetImports((CSharpSyntaxNode)tree.GetRoot(), basesBeingResolved: null); } /// <summary> /// Imports from all previous submissions. /// </summary> internal Imports GetPreviousSubmissionImports() => _previousSubmissionImports.Value; private Imports ExpandPreviousSubmissionImports() { Debug.Assert(this.IsSubmission); var previous = this.PreviousSubmission; if (previous == null) { return Imports.Empty; } return Imports.ExpandPreviousSubmissionImports(previous.GetPreviousSubmissionImports(), this).Concat( Imports.ExpandPreviousSubmissionImports(previous.GetSubmissionImports(), this)); } internal AliasSymbol GlobalNamespaceAlias { get { return _globalNamespaceAlias.Value; } } /// <summary> /// Get the symbol for the predefined type from the COR Library referenced by this compilation. /// </summary> internal new NamedTypeSymbol GetSpecialType(SpecialType specialType) { if (specialType <= SpecialType.None || specialType > SpecialType.Count) { throw new ArgumentOutOfRangeException(nameof(specialType), $"Unexpected SpecialType: '{(int)specialType}'."); } NamedTypeSymbol result; if (IsTypeMissing(specialType)) { MetadataTypeName emittedName = MetadataTypeName.FromFullName(specialType.GetMetadataName(), useCLSCompliantNameArityEncoding: true); result = new MissingMetadataTypeSymbol.TopLevel(Assembly.CorLibrary.Modules[0], ref emittedName, specialType); } else { result = Assembly.GetSpecialType(specialType); } Debug.Assert(result.SpecialType == specialType); return result; } /// <summary> /// Get the symbol for the predefined type member from the COR Library referenced by this compilation. /// </summary> internal Symbol GetSpecialTypeMember(SpecialMember specialMember) { return Assembly.GetSpecialTypeMember(specialMember); } internal override ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember) { return GetSpecialTypeMember(specialMember); } internal TypeSymbol GetTypeByReflectionType(Type type, BindingDiagnosticBag diagnostics) { var result = Assembly.GetTypeByReflectionType(type, includeReferences: true); if ((object)result == null) { var errorType = new ExtendedErrorTypeSymbol(this, type.Name, 0, CreateReflectionTypeNotFoundError(type)); diagnostics.Add(errorType.ErrorInfo, NoLocation.Singleton); result = errorType; } return result; } private static CSDiagnosticInfo CreateReflectionTypeNotFoundError(Type type) { // The type or namespace name '{0}' could not be found in the global namespace (are you missing an assembly reference?) return new CSDiagnosticInfo( ErrorCode.ERR_GlobalSingleTypeNameNotFound, new object[] { type.AssemblyQualifiedName ?? "" }, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty ); } protected override ITypeSymbol? CommonScriptGlobalsType => GetHostObjectTypeSymbol()?.GetPublicSymbol(); internal TypeSymbol? GetHostObjectTypeSymbol() { if (HostObjectType != null && _lazyHostObjectTypeSymbol is null) { TypeSymbol symbol = Assembly.GetTypeByReflectionType(HostObjectType, includeReferences: true); if ((object)symbol == null) { MetadataTypeName mdName = MetadataTypeName.FromNamespaceAndTypeName(HostObjectType.Namespace ?? String.Empty, HostObjectType.Name, useCLSCompliantNameArityEncoding: true); symbol = new MissingMetadataTypeSymbol.TopLevel( new MissingAssemblySymbol(AssemblyIdentity.FromAssemblyDefinition(HostObjectType.GetTypeInfo().Assembly)).Modules[0], ref mdName, SpecialType.None, CreateReflectionTypeNotFoundError(HostObjectType)); } Interlocked.CompareExchange(ref _lazyHostObjectTypeSymbol, symbol, null); } return _lazyHostObjectTypeSymbol; } internal SynthesizedInteractiveInitializerMethod? GetSubmissionInitializer() { return (IsSubmission && ScriptClass is object) ? ScriptClass.GetScriptInitializer() : null; } /// <summary> /// Gets the type within the compilation's assembly and all referenced assemblies (other than /// those that can only be referenced via an extern alias) using its canonical CLR metadata name. /// </summary> internal new NamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName) { return this.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: true, isWellKnownType: false, conflicts: out var _); } /// <summary> /// The TypeSymbol for the type 'dynamic' in this Compilation. /// </summary> internal new TypeSymbol DynamicType { get { return AssemblySymbol.DynamicType; } } /// <summary> /// The NamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of /// Error if there was no COR Library in this Compilation. /// </summary> internal new NamedTypeSymbol ObjectType { get { return this.Assembly.ObjectType; } } internal bool DeclaresTheObjectClass { get { return SourceAssembly.DeclaresTheObjectClass; } } internal new MethodSymbol? GetEntryPoint(CancellationToken cancellationToken) { EntryPoint entryPoint = GetEntryPointAndDiagnostics(cancellationToken); return entryPoint.MethodSymbol; } internal EntryPoint GetEntryPointAndDiagnostics(CancellationToken cancellationToken) { if (_lazyEntryPoint == null) { EntryPoint? entryPoint; var simpleProgramEntryPointSymbol = SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(this); if (!this.Options.OutputKind.IsApplication() && (this.ScriptClass is null)) { if (simpleProgramEntryPointSymbol is object) { var diagnostics = BindingDiagnosticBag.GetInstance(); diagnostics.Add(ErrorCode.ERR_SimpleProgramNotAnExecutable, simpleProgramEntryPointSymbol.ReturnTypeSyntax.Location); entryPoint = new EntryPoint(null, diagnostics.ToReadOnlyAndFree()); } else { entryPoint = EntryPoint.None; } } else { entryPoint = null; if (this.Options.MainTypeName != null && !this.Options.MainTypeName.IsValidClrTypeName()) { Debug.Assert(!this.Options.Errors.IsDefaultOrEmpty); entryPoint = EntryPoint.None; } if (entryPoint is null) { ImmutableBindingDiagnostic<AssemblySymbol> diagnostics; var entryPointMethod = FindEntryPoint(simpleProgramEntryPointSymbol, cancellationToken, out diagnostics); entryPoint = new EntryPoint(entryPointMethod, diagnostics); } if (this.Options.MainTypeName != null && simpleProgramEntryPointSymbol is object) { var diagnostics = DiagnosticBag.GetInstance(); diagnostics.Add(ErrorCode.ERR_SimpleProgramDisallowsMainType, NoLocation.Singleton); entryPoint = new EntryPoint(entryPoint.MethodSymbol, new ImmutableBindingDiagnostic<AssemblySymbol>( entryPoint.Diagnostics.Diagnostics.Concat(diagnostics.ToReadOnlyAndFree()), entryPoint.Diagnostics.Dependencies)); } } Interlocked.CompareExchange(ref _lazyEntryPoint, entryPoint, null); } return _lazyEntryPoint; } private MethodSymbol? FindEntryPoint(MethodSymbol? simpleProgramEntryPointSymbol, CancellationToken cancellationToken, out ImmutableBindingDiagnostic<AssemblySymbol> sealedDiagnostics) { var diagnostics = BindingDiagnosticBag.GetInstance(); RoslynDebug.Assert(diagnostics.DiagnosticBag is object); var entryPointCandidates = ArrayBuilder<MethodSymbol>.GetInstance(); try { NamedTypeSymbol? mainType; string? mainTypeName = this.Options.MainTypeName; NamespaceSymbol globalNamespace = this.SourceModule.GlobalNamespace; var scriptClass = this.ScriptClass; if (mainTypeName != null) { // Global code is the entry point, ignore all other Mains. if (scriptClass is object) { // CONSIDER: we could use the symbol instead of just the name. diagnostics.Add(ErrorCode.WRN_MainIgnored, NoLocation.Singleton, mainTypeName); return scriptClass.GetScriptEntryPoint(); } var mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split('.')).OfMinimalArity(); if (mainTypeOrNamespace is null) { diagnostics.Add(ErrorCode.ERR_MainClassNotFound, NoLocation.Singleton, mainTypeName); return null; } mainType = mainTypeOrNamespace as NamedTypeSymbol; if (mainType is null || mainType.IsGenericType || (mainType.TypeKind != TypeKind.Class && mainType.TypeKind != TypeKind.Struct && !mainType.IsInterface)) { diagnostics.Add(ErrorCode.ERR_MainClassNotClass, mainTypeOrNamespace.Locations.First(), mainTypeOrNamespace); return null; } AddEntryPointCandidates(entryPointCandidates, mainType.GetMembersUnordered()); } else { mainType = null; AddEntryPointCandidates( entryPointCandidates, this.GetSymbolsWithNameCore(WellKnownMemberNames.EntryPointMethodName, SymbolFilter.Member, cancellationToken)); // Global code is the entry point, ignore all other Mains. if (scriptClass is object || simpleProgramEntryPointSymbol is object) { foreach (var main in entryPointCandidates) { if (main is not SynthesizedSimpleProgramEntryPointSymbol) { diagnostics.Add(ErrorCode.WRN_MainIgnored, main.Locations.First(), main); } } if (scriptClass is object) { return scriptClass.GetScriptEntryPoint(); } RoslynDebug.Assert(simpleProgramEntryPointSymbol is object); entryPointCandidates.Clear(); entryPointCandidates.Add(simpleProgramEntryPointSymbol); } } // Validity and diagnostics are also tracked because they must be conditionally handled // if there are not any "traditional" entrypoints found. var taskEntryPoints = ArrayBuilder<(bool IsValid, MethodSymbol Candidate, BindingDiagnosticBag SpecificDiagnostics)>.GetInstance(); // These diagnostics (warning only) are added to the compilation only if // there were not any main methods found. var noMainFoundDiagnostics = BindingDiagnosticBag.GetInstance(diagnostics); RoslynDebug.Assert(noMainFoundDiagnostics.DiagnosticBag is object); bool checkValid(MethodSymbol candidate, bool isCandidate, BindingDiagnosticBag specificDiagnostics) { if (!isCandidate) { noMainFoundDiagnostics.Add(ErrorCode.WRN_InvalidMainSig, candidate.Locations.First(), candidate); noMainFoundDiagnostics.AddRange(specificDiagnostics); return false; } if (candidate.IsGenericMethod || candidate.ContainingType.IsGenericType) { // a single error for partial methods: noMainFoundDiagnostics.Add(ErrorCode.WRN_MainCantBeGeneric, candidate.Locations.First(), candidate); return false; } return true; } var viableEntryPoints = ArrayBuilder<MethodSymbol>.GetInstance(); foreach (var candidate in entryPointCandidates) { var perCandidateBag = BindingDiagnosticBag.GetInstance(diagnostics); var (IsCandidate, IsTaskLike) = HasEntryPointSignature(candidate, perCandidateBag); if (IsTaskLike) { taskEntryPoints.Add((IsCandidate, candidate, perCandidateBag)); } else { if (checkValid(candidate, IsCandidate, perCandidateBag)) { if (candidate.IsAsync) { diagnostics.Add(ErrorCode.ERR_NonTaskMainCantBeAsync, candidate.Locations.First(), candidate); } else { diagnostics.AddRange(perCandidateBag); viableEntryPoints.Add(candidate); } } perCandidateBag.Free(); } } if (viableEntryPoints.Count == 0) { foreach (var (IsValid, Candidate, SpecificDiagnostics) in taskEntryPoints) { if (checkValid(Candidate, IsValid, SpecificDiagnostics) && CheckFeatureAvailability(Candidate.ExtractReturnTypeSyntax(), MessageID.IDS_FeatureAsyncMain, diagnostics)) { diagnostics.AddRange(SpecificDiagnostics); viableEntryPoints.Add(Candidate); } } } else if (LanguageVersion >= MessageID.IDS_FeatureAsyncMain.RequiredVersion() && taskEntryPoints.Count > 0) { var taskCandidates = taskEntryPoints.SelectAsArray(s => (Symbol)s.Candidate); var taskLocations = taskCandidates.SelectAsArray(s => s.Locations[0]); foreach (var candidate in taskCandidates) { // Method '{0}' will not be used as an entry point because a synchronous entry point '{1}' was found. var info = new CSDiagnosticInfo( ErrorCode.WRN_SyncAndAsyncEntryPoints, args: new object[] { candidate, viableEntryPoints[0] }, symbols: taskCandidates, additionalLocations: taskLocations); diagnostics.Add(new CSDiagnostic(info, candidate.Locations[0])); } } foreach (var (_, _, SpecificDiagnostics) in taskEntryPoints) { SpecificDiagnostics.Free(); } if (viableEntryPoints.Count == 0) { diagnostics.AddRange(noMainFoundDiagnostics); } else if (mainType is null) { // Filters out diagnostics so that only InvalidMainSig and MainCant'BeGeneric are left. // The reason that Error diagnostics can end up in `noMainFoundDiagnostics` is when // HasEntryPointSignature yields some Error Diagnostics when people implement Task or Task<T> incorrectly. // // We can't add those Errors to the general diagnostics bag because it would break previously-working programs. // The fact that these warnings are not added when csc is invoked with /main is possibly a bug, and is tracked at // https://github.com/dotnet/roslyn/issues/18964 foreach (var diagnostic in noMainFoundDiagnostics.DiagnosticBag.AsEnumerable()) { if (diagnostic.Code == (int)ErrorCode.WRN_InvalidMainSig || diagnostic.Code == (int)ErrorCode.WRN_MainCantBeGeneric) { diagnostics.Add(diagnostic); } } diagnostics.AddDependencies(noMainFoundDiagnostics); } MethodSymbol? entryPoint = null; if (viableEntryPoints.Count == 0) { if (mainType is null) { diagnostics.Add(ErrorCode.ERR_NoEntryPoint, NoLocation.Singleton); } else { diagnostics.Add(ErrorCode.ERR_NoMainInClass, mainType.Locations.First(), mainType); } } else { foreach (var viableEntryPoint in viableEntryPoints) { if (viableEntryPoint.GetUnmanagedCallersOnlyAttributeData(forceComplete: true) is { } data) { Debug.Assert(!ReferenceEquals(data, UnmanagedCallersOnlyAttributeData.Uninitialized)); Debug.Assert(!ReferenceEquals(data, UnmanagedCallersOnlyAttributeData.AttributePresentDataNotBound)); diagnostics.Add(ErrorCode.ERR_EntryPointCannotBeUnmanagedCallersOnly, viableEntryPoint.Locations.First()); } } if (viableEntryPoints.Count > 1) { viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance); var info = new CSDiagnosticInfo( ErrorCode.ERR_MultipleEntryPoints, args: Array.Empty<object>(), symbols: viableEntryPoints.OfType<Symbol>().AsImmutable(), additionalLocations: viableEntryPoints.Select(m => m.Locations.First()).OfType<Location>().AsImmutable()); diagnostics.Add(new CSDiagnostic(info, viableEntryPoints.First().Locations.First())); } else { entryPoint = viableEntryPoints[0]; } } taskEntryPoints.Free(); viableEntryPoints.Free(); noMainFoundDiagnostics.Free(); return entryPoint; } finally { entryPointCandidates.Free(); sealedDiagnostics = diagnostics.ToReadOnlyAndFree(); } } private static void AddEntryPointCandidates( ArrayBuilder<MethodSymbol> entryPointCandidates, IEnumerable<Symbol> members) { foreach (var member in members) { if (member is MethodSymbol method && method.IsEntryPointCandidate) { entryPointCandidates.Add(method); } } } internal bool ReturnsAwaitableToVoidOrInt(MethodSymbol method, BindingDiagnosticBag diagnostics) { // Common case optimization if (method.ReturnType.IsVoidType() || method.ReturnType.SpecialType == SpecialType.System_Int32) { return false; } if (!(method.ReturnType is NamedTypeSymbol namedType)) { return false; } // Early bail so we only ever check things that are System.Threading.Tasks.Task(<T>) if (!(TypeSymbol.Equals(namedType.ConstructedFrom, GetWellKnownType(WellKnownType.System_Threading_Tasks_Task), TypeCompareKind.ConsiderEverything2) || TypeSymbol.Equals(namedType.ConstructedFrom, GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T), TypeCompareKind.ConsiderEverything2))) { return false; } var syntax = method.ExtractReturnTypeSyntax(); var dumbInstance = new BoundLiteral(syntax, ConstantValue.Null, namedType); var binder = GetBinder(syntax); BoundExpression? result; var success = binder.GetAwaitableExpressionInfo(dumbInstance, out result, syntax, diagnostics); RoslynDebug.Assert(!namedType.IsDynamic()); return success && (result!.Type!.IsVoidType() || result.Type!.SpecialType == SpecialType.System_Int32); } /// <summary> /// Checks if the method has an entry point compatible signature, i.e. /// - the return type is either void, int, or returns a <see cref="System.Threading.Tasks.Task" />, /// or <see cref="System.Threading.Tasks.Task{T}" /> where the return type of GetAwaiter().GetResult() /// is either void or int. /// - has either no parameter or a single parameter of type string[] /// </summary> internal (bool IsCandidate, bool IsTaskLike) HasEntryPointSignature(MethodSymbol method, BindingDiagnosticBag bag) { if (method.IsVararg) { return (false, false); } TypeSymbol returnType = method.ReturnType; bool returnsTaskOrTaskOfInt = false; if (returnType.SpecialType != SpecialType.System_Int32 && !returnType.IsVoidType()) { // Never look for ReturnsAwaitableToVoidOrInt on int32 or void returnsTaskOrTaskOfInt = ReturnsAwaitableToVoidOrInt(method, bag); if (!returnsTaskOrTaskOfInt) { return (false, false); } } if (method.RefKind != RefKind.None) { return (false, returnsTaskOrTaskOfInt); } if (method.Parameters.Length == 0) { return (true, returnsTaskOrTaskOfInt); } if (method.Parameters.Length > 1) { return (false, returnsTaskOrTaskOfInt); } if (!method.ParameterRefKinds.IsDefault) { return (false, returnsTaskOrTaskOfInt); } var firstType = method.Parameters[0].TypeWithAnnotations; if (firstType.TypeKind != TypeKind.Array) { return (false, returnsTaskOrTaskOfInt); } var array = (ArrayTypeSymbol)firstType.Type; return (array.IsSZArray && array.ElementType.SpecialType == SpecialType.System_String, returnsTaskOrTaskOfInt); } internal override bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code) => code == (int)ErrorCode.ERR_NoTypeDef; internal class EntryPoint { public readonly MethodSymbol? MethodSymbol; public readonly ImmutableBindingDiagnostic<AssemblySymbol> Diagnostics; public static readonly EntryPoint None = new EntryPoint(null, ImmutableBindingDiagnostic<AssemblySymbol>.Empty); public EntryPoint(MethodSymbol? methodSymbol, ImmutableBindingDiagnostic<AssemblySymbol> diagnostics) { this.MethodSymbol = methodSymbol; this.Diagnostics = diagnostics; } } internal bool MightContainNoPiaLocalTypes() { return SourceAssembly.MightContainNoPiaLocalTypes(); } // NOTE(cyrusn): There is a bit of a discoverability problem with this method and the same // named method in SyntaxTreeSemanticModel. Technically, i believe these are the appropriate // locations for these methods. This method has no dependencies on anything but the // compilation, while the other method needs a bindings object to determine what bound node // an expression syntax binds to. Perhaps when we document these methods we should explain // where a user can find the other. /// <summary> /// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/>. /// </summary> /// <param name="source">Source type of value to be converted</param> /// <param name="destination">Destination type of value to be converted</param> /// <returns>A <see cref="Conversion"/> that classifies the conversion from the /// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns> public Conversion ClassifyConversion(ITypeSymbol source, ITypeSymbol destination) { // Note that it is possible for there to be both an implicit user-defined conversion // and an explicit built-in conversion from source to destination. In that scenario // this method returns the implicit conversion. if ((object)source == null) { throw new ArgumentNullException(nameof(source)); } if ((object)destination == null) { throw new ArgumentNullException(nameof(destination)); } TypeSymbol? cssource = source.EnsureCSharpSymbolOrNull(nameof(source)); TypeSymbol? csdest = destination.EnsureCSharpSymbolOrNull(nameof(destination)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return Conversions.ClassifyConversionFromType(cssource, csdest, ref discardedUseSiteInfo); } /// <summary> /// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according /// to this compilation's programming language. /// </summary> /// <param name="source">Source type of value to be converted</param> /// <param name="destination">Destination type of value to be converted</param> /// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the /// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns> public override CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination) { return ClassifyConversion(source, destination).ToCommonConversion(); } internal override IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol? destination, out ConstantValue? constantValue) { constantValue = null; if (destination is null) { return Conversion.NoConversion; } ITypeSymbol? sourceType = source.Type; ConstantValue? sourceConstantValue = source.GetConstantValue(); if (sourceType is null) { if (sourceConstantValue is { IsNull: true } && destination.IsReferenceType) { constantValue = sourceConstantValue; return Conversion.NullLiteral; } return Conversion.NoConversion; } Conversion result = ClassifyConversion(sourceType, destination); if (result.IsReference && sourceConstantValue is { IsNull: true }) { constantValue = sourceConstantValue; } return result; } /// <summary> /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the /// COR Library in this Compilation. /// </summary> internal ArrayTypeSymbol CreateArrayTypeSymbol(TypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.Oblivious) { if ((object)elementType == null) { throw new ArgumentNullException(nameof(elementType)); } if (rank < 1) { throw new ArgumentException(nameof(rank)); } return ArrayTypeSymbol.CreateCSharpArray(this.Assembly, TypeWithAnnotations.Create(elementType, elementNullableAnnotation), rank); } /// <summary> /// Returns a new PointerTypeSymbol representing a pointer type tied to a type in this Compilation. /// </summary> internal PointerTypeSymbol CreatePointerTypeSymbol(TypeSymbol elementType, NullableAnnotation elementNullableAnnotation = NullableAnnotation.Oblivious) { if ((object)elementType == null) { throw new ArgumentNullException(nameof(elementType)); } return new PointerTypeSymbol(TypeWithAnnotations.Create(elementType, elementNullableAnnotation)); } private protected override bool IsSymbolAccessibleWithinCore( ISymbol symbol, ISymbol within, ITypeSymbol? throughType) { Symbol? symbol0 = symbol.EnsureCSharpSymbolOrNull(nameof(symbol)); Symbol? within0 = within.EnsureCSharpSymbolOrNull(nameof(within)); TypeSymbol? throughType0 = throughType.EnsureCSharpSymbolOrNull(nameof(throughType)); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return within0.Kind == SymbolKind.Assembly ? AccessCheck.IsSymbolAccessible(symbol0, (AssemblySymbol)within0, ref discardedUseSiteInfo) : AccessCheck.IsSymbolAccessible(symbol0, (NamedTypeSymbol)within0, ref discardedUseSiteInfo, throughType0); } [Obsolete("Compilation.IsSymbolAccessibleWithin is not designed for use within the compilers", true)] internal new bool IsSymbolAccessibleWithin( ISymbol symbol, ISymbol within, ITypeSymbol? throughType = null) { throw new NotImplementedException(); } private ConcurrentSet<MethodSymbol>? _moduleInitializerMethods; internal void AddModuleInitializerMethod(MethodSymbol method) { Debug.Assert(!_declarationDiagnosticsFrozen); LazyInitializer.EnsureInitialized(ref _moduleInitializerMethods).Add(method); } #endregion #region Binding /// <summary> /// Gets a new SyntaxTreeSemanticModel for the specified syntax tree. /// </summary> public new SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) { if (syntaxTree == null) { throw new ArgumentNullException(nameof(syntaxTree)); } if (!_syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree)) { throw new ArgumentException(CSharpResources.SyntaxTreeNotFound, nameof(syntaxTree)); } SemanticModel? model = null; if (SemanticModelProvider != null) { model = SemanticModelProvider.GetSemanticModel(syntaxTree, this, ignoreAccessibility); Debug.Assert(model != null); } return model ?? CreateSemanticModel(syntaxTree, ignoreAccessibility); } internal override SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) => new SyntaxTreeSemanticModel(this, syntaxTree, ignoreAccessibility); // When building symbols from the declaration table (lazily), or inside a type, or when // compiling a method body, we may not have a BinderContext in hand for the enclosing // scopes. Therefore, we build them when needed (and cache them) using a ContextBuilder. // Since a ContextBuilder is only a cache, and the identity of the ContextBuilders and // BinderContexts have no semantic meaning, we can reuse them or rebuild them, whichever is // most convenient. We store them using weak references so that GC pressure will cause them // to be recycled. private WeakReference<BinderFactory>[]? _binderFactories; private WeakReference<BinderFactory>[]? _ignoreAccessibilityBinderFactories; internal BinderFactory GetBinderFactory(SyntaxTree syntaxTree, bool ignoreAccessibility = false) { if (ignoreAccessibility && SynthesizedSimpleProgramEntryPointSymbol.GetSimpleProgramEntryPoint(this) is object) { return GetBinderFactory(syntaxTree, ignoreAccessibility: true, ref _ignoreAccessibilityBinderFactories); } return GetBinderFactory(syntaxTree, ignoreAccessibility: false, ref _binderFactories); } private BinderFactory GetBinderFactory(SyntaxTree syntaxTree, bool ignoreAccessibility, ref WeakReference<BinderFactory>[]? cachedBinderFactories) { Debug.Assert(System.Runtime.CompilerServices.Unsafe.AreSame(ref cachedBinderFactories, ref ignoreAccessibility ? ref _ignoreAccessibilityBinderFactories : ref _binderFactories)); var treeNum = GetSyntaxTreeOrdinal(syntaxTree); WeakReference<BinderFactory>[]? binderFactories = cachedBinderFactories; if (binderFactories == null) { binderFactories = new WeakReference<BinderFactory>[this.SyntaxTrees.Length]; binderFactories = Interlocked.CompareExchange(ref cachedBinderFactories, binderFactories, null) ?? binderFactories; } BinderFactory? previousFactory; var previousWeakReference = binderFactories[treeNum]; if (previousWeakReference != null && previousWeakReference.TryGetTarget(out previousFactory)) { return previousFactory; } return AddNewFactory(syntaxTree, ignoreAccessibility, ref binderFactories[treeNum]); } private BinderFactory AddNewFactory(SyntaxTree syntaxTree, bool ignoreAccessibility, [NotNull] ref WeakReference<BinderFactory>? slot) { var newFactory = new BinderFactory(this, syntaxTree, ignoreAccessibility); var newWeakReference = new WeakReference<BinderFactory>(newFactory); while (true) { BinderFactory? previousFactory; WeakReference<BinderFactory>? previousWeakReference = slot; if (previousWeakReference != null && previousWeakReference.TryGetTarget(out previousFactory)) { Debug.Assert(slot is object); return previousFactory; } if (Interlocked.CompareExchange(ref slot!, newWeakReference, previousWeakReference) == previousWeakReference) { return newFactory; } } } internal Binder GetBinder(CSharpSyntaxNode syntax) { return GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax); } private AliasSymbol CreateGlobalNamespaceAlias() { return AliasSymbol.CreateGlobalNamespaceAlias(this.GlobalNamespace); } private void CompleteTree(SyntaxTree tree) { if (_lazyCompilationUnitCompletedTrees == null) Interlocked.CompareExchange(ref _lazyCompilationUnitCompletedTrees, new HashSet<SyntaxTree>(), null); lock (_lazyCompilationUnitCompletedTrees) { if (_lazyCompilationUnitCompletedTrees.Add(tree)) { // signal the end of the compilation unit EventQueue?.TryEnqueue(new CompilationUnitCompletedEvent(this, tree)); if (_lazyCompilationUnitCompletedTrees.Count == this.SyntaxTrees.Length) { // if that was the last tree, signal the end of compilation CompleteCompilationEventQueue_NoLock(); } } } } internal override void ReportUnusedImports(DiagnosticBag diagnostics, CancellationToken cancellationToken) { ReportUnusedImports(filterTree: null, new BindingDiagnosticBag(diagnostics), cancellationToken); } private void ReportUnusedImports(SyntaxTree? filterTree, BindingDiagnosticBag diagnostics, CancellationToken cancellationToken) { if (_lazyImportInfos != null && (filterTree is null || ReportUnusedImportsInTree(filterTree))) { PooledHashSet<NamespaceSymbol>? externAliasesToCheck = null; if (diagnostics.DependenciesBag is object) { externAliasesToCheck = PooledHashSet<NamespaceSymbol>.GetInstance(); } foreach (var pair in _lazyImportInfos) { cancellationToken.ThrowIfCancellationRequested(); ImportInfo info = pair.Key; SyntaxTree infoTree = info.Tree; if ((filterTree == null || filterTree == infoTree) && ReportUnusedImportsInTree(infoTree)) { TextSpan infoSpan = info.Span; if (!this.IsImportDirectiveUsed(infoTree, infoSpan.Start)) { ErrorCode code = info.Kind == SyntaxKind.ExternAliasDirective ? ErrorCode.HDN_UnusedExternAlias : ErrorCode.HDN_UnusedUsingDirective; diagnostics.Add(code, infoTree.GetLocation(infoSpan)); } else if (diagnostics.DependenciesBag is object) { RoslynDebug.Assert(externAliasesToCheck is object); ImmutableArray<AssemblySymbol> dependencies = pair.Value; if (!dependencies.IsDefaultOrEmpty) { diagnostics.AddDependencies(dependencies); } else if (info.Kind == SyntaxKind.ExternAliasDirective) { // Record targets of used extern aliases var node = info.Tree.GetRoot(cancellationToken).FindToken(info.Span.Start, findInsideTrivia: false). Parent!.FirstAncestorOrSelf<ExternAliasDirectiveSyntax>(); if (node is object && GetExternAliasTarget(node.Identifier.ValueText, out NamespaceSymbol target)) { externAliasesToCheck.Add(target); } } } } } if (externAliasesToCheck is object) { RoslynDebug.Assert(diagnostics.DependenciesBag is object); // We could do this check after we have built the transitive closure // in GetCompleteSetOfUsedAssemblies.completeTheSetOfUsedAssemblies. However, // the level of accuracy is probably not worth the complexity this would add. var bindingDiagnostics = new BindingDiagnosticBag(diagnosticBag: null, PooledHashSet<AssemblySymbol>.GetInstance()); RoslynDebug.Assert(bindingDiagnostics.DependenciesBag is object); foreach (var aliasedNamespace in externAliasesToCheck) { bindingDiagnostics.Clear(); bindingDiagnostics.AddAssembliesUsedByNamespaceReference(aliasedNamespace); // See if any of the references with the alias are registered as used. We can get in a situation when none of them are. // For example, when the alias was used in a doc comment, but nothing was found within it. We would get only a warning // in this case and no assembly marked as used. if (_lazyUsedAssemblyReferences?.IsEmpty == false || diagnostics.DependenciesBag.Count != 0) { foreach (var assembly in bindingDiagnostics.DependenciesBag) { if (_lazyUsedAssemblyReferences?.Contains(assembly) == true || diagnostics.DependenciesBag.Contains(assembly)) { bindingDiagnostics.DependenciesBag.Clear(); break; } } } diagnostics.AddDependencies(bindingDiagnostics); } bindingDiagnostics.Free(); externAliasesToCheck.Free(); } } CompleteTrees(filterTree); } internal override void CompleteTrees(SyntaxTree? filterTree) { // By definition, a tree is complete when all of its compiler diagnostics have been reported. // Since unused imports are the last thing we compute and report, a tree is complete when // the unused imports have been reported. if (EventQueue != null) { if (filterTree != null) { CompleteTree(filterTree); } else { foreach (var tree in this.SyntaxTrees) { CompleteTree(tree); } } } if (filterTree is null) { _usageOfUsingsRecordedInTrees = null; } } internal void RecordImport(UsingDirectiveSyntax syntax) { RecordImportInternal(syntax); } internal void RecordImport(ExternAliasDirectiveSyntax syntax) { RecordImportInternal(syntax); } private void RecordImportInternal(CSharpSyntaxNode syntax) { // Note: the suppression will be unnecessary once LazyInitializer is properly annotated LazyInitializer.EnsureInitialized(ref _lazyImportInfos)!. TryAdd(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), syntax.Span), default); } internal void RecordImportDependencies(UsingDirectiveSyntax syntax, ImmutableArray<AssemblySymbol> dependencies) { RoslynDebug.Assert(_lazyImportInfos is object); _lazyImportInfos.TryUpdate(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), syntax.Span), dependencies, default); } private struct ImportInfo : IEquatable<ImportInfo> { public readonly SyntaxTree Tree; public readonly SyntaxKind Kind; public readonly TextSpan Span; public ImportInfo(SyntaxTree tree, SyntaxKind kind, TextSpan span) { this.Tree = tree; this.Kind = kind; this.Span = span; } public override bool Equals(object? obj) { return (obj is ImportInfo) && Equals((ImportInfo)obj); } public bool Equals(ImportInfo other) { return other.Kind == this.Kind && other.Tree == this.Tree && other.Span == this.Span; } public override int GetHashCode() { return Hash.Combine(Tree, Span.Start); } } #endregion #region Diagnostics internal override CommonMessageProvider MessageProvider { get { return _syntaxAndDeclarations.MessageProvider; } } /// <summary> /// The bag in which semantic analysis should deposit its diagnostics. /// </summary> internal DiagnosticBag DeclarationDiagnostics { get { // We should only be placing diagnostics in this bag until // we are done gathering declaration diagnostics. Assert that is // the case. But since we have bugs (see https://github.com/dotnet/roslyn/issues/846) // we disable the assertion until they are fixed. Debug.Assert(!_declarationDiagnosticsFrozen || true); if (_lazyDeclarationDiagnostics == null) { var diagnostics = new DiagnosticBag(); Interlocked.CompareExchange(ref _lazyDeclarationDiagnostics, diagnostics, null); } return _lazyDeclarationDiagnostics; } } private DiagnosticBag? _lazyDeclarationDiagnostics; private bool _declarationDiagnosticsFrozen; /// <summary> /// A bag in which diagnostics that should be reported after code gen can be deposited. /// </summary> internal DiagnosticBag AdditionalCodegenWarnings { get { return _additionalCodegenWarnings; } } private readonly DiagnosticBag _additionalCodegenWarnings = new DiagnosticBag(); internal DeclarationTable Declarations { get { return _syntaxAndDeclarations.GetLazyState().DeclarationTable; } } internal MergedNamespaceDeclaration MergedRootDeclaration { get { return Declarations.GetMergedRoot(this); } } /// <summary> /// Gets the diagnostics produced during the parsing stage of a compilation. There are no diagnostics for declarations or accessor or /// method bodies, for example. /// </summary> public override ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(CompilationStage.Parse, false, cancellationToken); } /// <summary> /// Gets the diagnostics produced during symbol declaration headers. There are no diagnostics for accessor or /// method bodies, for example. /// </summary> public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(CompilationStage.Declare, false, cancellationToken); } /// <summary> /// Gets the diagnostics produced during the analysis of method bodies and field initializers. /// </summary> public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(CompilationStage.Compile, false, cancellationToken); } /// <summary> /// Gets the all the diagnostics for the compilation, including syntax, declaration, and binding. Does not /// include any diagnostics that might be produced during emit. /// </summary> public override ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default) { return GetDiagnostics(DefaultDiagnosticsStage, true, cancellationToken); } internal ImmutableArray<Diagnostic> GetDiagnostics(CompilationStage stage, bool includeEarlierStages, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); GetDiagnostics(stage, includeEarlierStages, diagnostics, cancellationToken); return diagnostics.ToReadOnlyAndFree(); } internal override void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default) { DiagnosticBag? builder = DiagnosticBag.GetInstance(); GetDiagnosticsWithoutFiltering(stage, includeEarlierStages, new BindingDiagnosticBag(builder), cancellationToken); // Before returning diagnostics, we filter warnings // to honor the compiler options (e.g., /nowarn, /warnaserror and /warn) and the pragmas. FilterAndAppendAndFreeDiagnostics(diagnostics, ref builder, cancellationToken); } private void GetDiagnosticsWithoutFiltering(CompilationStage stage, bool includeEarlierStages, BindingDiagnosticBag builder, CancellationToken cancellationToken) { RoslynDebug.Assert(builder.DiagnosticBag is object); if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages)) { var syntaxTrees = this.SyntaxTrees; if (this.Options.ConcurrentBuild) { RoslynParallel.For( 0, syntaxTrees.Length, UICultureUtilities.WithCurrentUICulture<int>(i => { var syntaxTree = syntaxTrees[i]; AppendLoadDirectiveDiagnostics(builder.DiagnosticBag, _syntaxAndDeclarations, syntaxTree); builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken)); }), cancellationToken); } else { foreach (var syntaxTree in syntaxTrees) { cancellationToken.ThrowIfCancellationRequested(); AppendLoadDirectiveDiagnostics(builder.DiagnosticBag, _syntaxAndDeclarations, syntaxTree); cancellationToken.ThrowIfCancellationRequested(); builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken)); } } var parseOptionsReported = new HashSet<ParseOptions>(); foreach (var syntaxTree in syntaxTrees) { cancellationToken.ThrowIfCancellationRequested(); if (!syntaxTree.Options.Errors.IsDefaultOrEmpty && parseOptionsReported.Add(syntaxTree.Options)) { var location = syntaxTree.GetLocation(TextSpan.FromBounds(0, 0)); foreach (var error in syntaxTree.Options.Errors) { builder.Add(error.WithLocation(location)); } } } } if (stage == CompilationStage.Declare || stage > CompilationStage.Declare && includeEarlierStages) { CheckAssemblyName(builder.DiagnosticBag); builder.AddRange(Options.Errors); if (Options.NullableContextOptions != NullableContextOptions.Disable && LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion() && _syntaxAndDeclarations.ExternalSyntaxTrees.Any()) { builder.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_NullableOptionNotAvailable, nameof(Options.NullableContextOptions), Options.NullableContextOptions, LanguageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion())), Location.None)); } cancellationToken.ThrowIfCancellationRequested(); // the set of diagnostics related to establishing references. builder.AddRange(GetBoundReferenceManager().Diagnostics); cancellationToken.ThrowIfCancellationRequested(); builder.AddRange(GetSourceDeclarationDiagnostics(cancellationToken: cancellationToken), allowMismatchInDependencyAccumulation: true); if (EventQueue != null && SyntaxTrees.Length == 0) { EnsureCompilationEventQueueCompleted(); } } cancellationToken.ThrowIfCancellationRequested(); if (stage == CompilationStage.Compile || stage > CompilationStage.Compile && includeEarlierStages) { var methodBodyDiagnostics = new BindingDiagnosticBag(DiagnosticBag.GetInstance(), builder.DependenciesBag is object ? new ConcurrentSet<AssemblySymbol>() : null); RoslynDebug.Assert(methodBodyDiagnostics.DiagnosticBag is object); GetDiagnosticsForAllMethodBodies(methodBodyDiagnostics, doLowering: false, cancellationToken); builder.AddRange(methodBodyDiagnostics); methodBodyDiagnostics.DiagnosticBag.Free(); } } private static void AppendLoadDirectiveDiagnostics(DiagnosticBag builder, SyntaxAndDeclarationManager syntaxAndDeclarations, SyntaxTree syntaxTree, Func<IEnumerable<Diagnostic>, IEnumerable<Diagnostic>>? locationFilterOpt = null) { ImmutableArray<LoadDirective> loadDirectives; if (syntaxAndDeclarations.GetLazyState().LoadDirectiveMap.TryGetValue(syntaxTree, out loadDirectives)) { Debug.Assert(!loadDirectives.IsEmpty); foreach (var directive in loadDirectives) { IEnumerable<Diagnostic> diagnostics = directive.Diagnostics; if (locationFilterOpt != null) { diagnostics = locationFilterOpt(diagnostics); } builder.AddRange(diagnostics); } } } // Do the steps in compilation to get the method body diagnostics, but don't actually generate // IL or emit an assembly. private void GetDiagnosticsForAllMethodBodies(BindingDiagnosticBag diagnostics, bool doLowering, CancellationToken cancellationToken) { RoslynDebug.Assert(diagnostics.DiagnosticBag is object); MethodCompiler.CompileMethodBodies( compilation: this, moduleBeingBuiltOpt: doLowering ? (PEModuleBuilder?)CreateModuleBuilder( emitOptions: EmitOptions.Default, debugEntryPoint: null, manifestResources: null, sourceLinkStream: null, embeddedTexts: null, testData: null, diagnostics: diagnostics.DiagnosticBag, cancellationToken: cancellationToken) : null, emittingPdb: false, emitTestCoverageData: false, hasDeclarationErrors: false, emitMethodBodies: false, diagnostics: diagnostics, filterOpt: null, cancellationToken: cancellationToken); DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, diagnostics, cancellationToken); this.ReportUnusedImports(filterTree: null, diagnostics, cancellationToken); } private static bool IsDefinedOrImplementedInSourceTree(Symbol symbol, SyntaxTree tree, TextSpan? span) { if (symbol.IsDefinedInSourceTree(tree, span)) { return true; } if (symbol.Kind == SymbolKind.Method && symbol.IsImplicitlyDeclared && ((MethodSymbol)symbol).MethodKind == MethodKind.Constructor) { // Include implicitly declared constructor if containing type is included return IsDefinedOrImplementedInSourceTree(symbol.ContainingType, tree, span); } return false; } private ImmutableArray<Diagnostic> GetDiagnosticsForMethodBodiesInTree(SyntaxTree tree, TextSpan? span, CancellationToken cancellationToken) { var diagnostics = DiagnosticBag.GetInstance(); var bindingDiagnostics = new BindingDiagnosticBag(diagnostics); // Report unused directives only if computing diagnostics for the entire tree. // Otherwise we cannot determine if a particular directive is used outside of the given sub-span within the tree. bool reportUnusedUsings = (!span.HasValue || span.Value == tree.GetRoot(cancellationToken).FullSpan) && ReportUnusedImportsInTree(tree); bool recordUsageOfUsingsInAllTrees = false; if (reportUnusedUsings && UsageOfUsingsRecordedInTrees is not null) { foreach (var singleDeclaration in ((SourceNamespaceSymbol)SourceModule.GlobalNamespace).MergedDeclaration.Declarations) { if (singleDeclaration.SyntaxReference.SyntaxTree == tree) { if (singleDeclaration.HasGlobalUsings) { // Global Using directives can be used in any tree. Make sure we collect usage information from all of them. recordUsageOfUsingsInAllTrees = true; } break; } } } if (recordUsageOfUsingsInAllTrees && UsageOfUsingsRecordedInTrees?.IsEmpty == true) { Debug.Assert(reportUnusedUsings); // Simply compile the world compileMethodBodiesAndDocComments(filterTree: null, filterSpan: null, bindingDiagnostics, cancellationToken); _usageOfUsingsRecordedInTrees = null; } else { // Always compile the target tree compileMethodBodiesAndDocComments(filterTree: tree, filterSpan: span, bindingDiagnostics, cancellationToken); if (reportUnusedUsings) { registeredUsageOfUsingsInTree(tree); } // Compile other trees if we need to, but discard diagnostics from them. if (recordUsageOfUsingsInAllTrees) { Debug.Assert(reportUnusedUsings); var discarded = new BindingDiagnosticBag(DiagnosticBag.GetInstance()); Debug.Assert(discarded.DiagnosticBag is object); foreach (var otherTree in SyntaxTrees) { var trackingSet = UsageOfUsingsRecordedInTrees; if (trackingSet is null) { break; } if (!trackingSet.Contains(otherTree)) { compileMethodBodiesAndDocComments(filterTree: otherTree, filterSpan: null, discarded, cancellationToken); registeredUsageOfUsingsInTree(otherTree); discarded.DiagnosticBag.Clear(); } } discarded.DiagnosticBag.Free(); } } if (reportUnusedUsings) { ReportUnusedImports(tree, bindingDiagnostics, cancellationToken); } return diagnostics.ToReadOnlyAndFree(); void compileMethodBodiesAndDocComments(SyntaxTree? filterTree, TextSpan? filterSpan, BindingDiagnosticBag bindingDiagnostics, CancellationToken cancellationToken) { MethodCompiler.CompileMethodBodies( compilation: this, moduleBeingBuiltOpt: null, emittingPdb: false, emitTestCoverageData: false, hasDeclarationErrors: false, emitMethodBodies: false, diagnostics: bindingDiagnostics, filterOpt: filterTree is object ? (Predicate<Symbol>?)(s => IsDefinedOrImplementedInSourceTree(s, filterTree, filterSpan)) : (Predicate<Symbol>?)null, cancellationToken: cancellationToken); DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, bindingDiagnostics, cancellationToken, filterTree, filterSpan); } void registeredUsageOfUsingsInTree(SyntaxTree tree) { var current = UsageOfUsingsRecordedInTrees; while (true) { if (current is null) { break; } var updated = current.Add(tree); if ((object)updated == current) { break; } if (updated.Count == SyntaxTrees.Length) { _usageOfUsingsRecordedInTrees = null; break; } var recent = Interlocked.CompareExchange(ref _usageOfUsingsRecordedInTrees, updated, current); if (recent == (object)current) { break; } current = recent; } } } private ImmutableBindingDiagnostic<AssemblySymbol> GetSourceDeclarationDiagnostics(SyntaxTree? syntaxTree = null, TextSpan? filterSpanWithinTree = null, Func<IEnumerable<Diagnostic>, SyntaxTree, TextSpan?, IEnumerable<Diagnostic>>? locationFilterOpt = null, CancellationToken cancellationToken = default) { UsingsFromOptions.Complete(this, cancellationToken); SourceLocation? location = null; if (syntaxTree != null) { var root = syntaxTree.GetRoot(cancellationToken); location = filterSpanWithinTree.HasValue ? new SourceLocation(syntaxTree, filterSpanWithinTree.Value) : new SourceLocation(root); } Assembly.ForceComplete(location, cancellationToken); if (syntaxTree is null) { // Don't freeze the compilation if we're getting // diagnostics for a single tree _declarationDiagnosticsFrozen = true; // Also freeze generated attribute flags. // Symbols bound after getting the declaration // diagnostics shouldn't need to modify the flags. _needsGeneratedAttributes_IsFrozen = true; } var result = _lazyDeclarationDiagnostics?.AsEnumerable() ?? Enumerable.Empty<Diagnostic>(); if (locationFilterOpt != null) { RoslynDebug.Assert(syntaxTree != null); result = locationFilterOpt(result, syntaxTree, filterSpanWithinTree); } // NOTE: Concatenate the CLS diagnostics *after* filtering by tree/span, because they're already filtered. ImmutableBindingDiagnostic<AssemblySymbol> clsDiagnostics = GetClsComplianceDiagnostics(syntaxTree, filterSpanWithinTree, cancellationToken); return new ImmutableBindingDiagnostic<AssemblySymbol>(result.AsImmutable().Concat(clsDiagnostics.Diagnostics), clsDiagnostics.Dependencies); } private ImmutableBindingDiagnostic<AssemblySymbol> GetClsComplianceDiagnostics(SyntaxTree? syntaxTree, TextSpan? filterSpanWithinTree, CancellationToken cancellationToken) { if (syntaxTree != null) { var builder = BindingDiagnosticBag.GetInstance(withDiagnostics: true, withDependencies: false); ClsComplianceChecker.CheckCompliance(this, builder, cancellationToken, syntaxTree, filterSpanWithinTree); return builder.ToReadOnlyAndFree(); } if (_lazyClsComplianceDiagnostics.IsDefault || _lazyClsComplianceDependencies.IsDefault) { var builder = BindingDiagnosticBag.GetInstance(); ClsComplianceChecker.CheckCompliance(this, builder, cancellationToken); var result = builder.ToReadOnlyAndFree(); ImmutableInterlocked.InterlockedInitialize(ref _lazyClsComplianceDependencies, result.Dependencies); ImmutableInterlocked.InterlockedInitialize(ref _lazyClsComplianceDiagnostics, result.Diagnostics); } Debug.Assert(!_lazyClsComplianceDependencies.IsDefault); Debug.Assert(!_lazyClsComplianceDiagnostics.IsDefault); return new ImmutableBindingDiagnostic<AssemblySymbol>(_lazyClsComplianceDiagnostics, _lazyClsComplianceDependencies); } private static IEnumerable<Diagnostic> FilterDiagnosticsByLocation(IEnumerable<Diagnostic> diagnostics, SyntaxTree tree, TextSpan? filterSpanWithinTree) { foreach (var diagnostic in diagnostics) { if (diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree)) { yield return diagnostic; } } } internal ImmutableArray<Diagnostic> GetDiagnosticsForSyntaxTree( CompilationStage stage, SyntaxTree syntaxTree, TextSpan? filterSpanWithinTree, bool includeEarlierStages, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); DiagnosticBag? builder = DiagnosticBag.GetInstance(); if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages)) { AppendLoadDirectiveDiagnostics(builder, _syntaxAndDeclarations, syntaxTree, diagnostics => FilterDiagnosticsByLocation(diagnostics, syntaxTree, filterSpanWithinTree)); var syntaxDiagnostics = syntaxTree.GetDiagnostics(cancellationToken); syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, syntaxTree, filterSpanWithinTree); builder.AddRange(syntaxDiagnostics); } cancellationToken.ThrowIfCancellationRequested(); if (stage == CompilationStage.Declare || (stage > CompilationStage.Declare && includeEarlierStages)) { var declarationDiagnostics = GetSourceDeclarationDiagnostics(syntaxTree, filterSpanWithinTree, FilterDiagnosticsByLocation, cancellationToken); // re-enabling/fixing the below assert is tracked by https://github.com/dotnet/roslyn/issues/21020 // Debug.Assert(declarationDiagnostics.All(d => d.HasIntersectingLocation(syntaxTree, filterSpanWithinTree))); builder.AddRange(declarationDiagnostics.Diagnostics); } cancellationToken.ThrowIfCancellationRequested(); if (stage == CompilationStage.Compile || (stage > CompilationStage.Compile && includeEarlierStages)) { //remove some errors that don't have locations in the tree, like "no suitable main method." //Members in trees other than the one being examined are not compiled. This includes field //initializers which can result in 'field is never initialized' warnings for fields in partial //types when the field is in a different source file than the one for which we're getting diagnostics. //For that reason the bag must be also filtered by tree. IEnumerable<Diagnostic> methodBodyDiagnostics = GetDiagnosticsForMethodBodiesInTree(syntaxTree, filterSpanWithinTree, cancellationToken); // TODO: Enable the below commented assert and remove the filtering code in the next line. // GetDiagnosticsForMethodBodiesInTree seems to be returning diagnostics with locations that don't satisfy the filter tree/span, this must be fixed. // Debug.Assert(methodBodyDiagnostics.All(d => DiagnosticContainsLocation(d, syntaxTree, filterSpanWithinTree))); methodBodyDiagnostics = FilterDiagnosticsByLocation(methodBodyDiagnostics, syntaxTree, filterSpanWithinTree); builder.AddRange(methodBodyDiagnostics); } // Before returning diagnostics, we filter warnings // to honor the compiler options (/nowarn, /warnaserror and /warn) and the pragmas. var result = DiagnosticBag.GetInstance(); FilterAndAppendAndFreeDiagnostics(result, ref builder, cancellationToken); return result.ToReadOnlyAndFree<Diagnostic>(); } #endregion #region Resources protected override void AppendDefaultVersionResource(Stream resourceStream) { var sourceAssembly = SourceAssembly; string fileVersion = sourceAssembly.FileVersion ?? sourceAssembly.Identity.Version.ToString(); Win32ResourceConversions.AppendVersionToResourceStream(resourceStream, !this.Options.OutputKind.IsApplication(), fileVersion: fileVersion, originalFileName: this.SourceModule.Name, internalName: this.SourceModule.Name, productVersion: sourceAssembly.InformationalVersion ?? fileVersion, fileDescription: sourceAssembly.Title ?? " ", //alink would give this a blank if nothing was supplied. assemblyVersion: sourceAssembly.Identity.Version, legalCopyright: sourceAssembly.Copyright ?? " ", //alink would give this a blank if nothing was supplied. legalTrademarks: sourceAssembly.Trademark, productName: sourceAssembly.Product, comments: sourceAssembly.Description, companyName: sourceAssembly.Company); } #endregion #region Emit internal override byte LinkerMajorVersion => 0x30; internal override bool IsDelaySigned { get { return SourceAssembly.IsDelaySigned; } } internal override StrongNameKeys StrongNameKeys { get { return SourceAssembly.StrongNameKeys; } } internal override CommonPEModuleBuilder? CreateModuleBuilder( EmitOptions emitOptions, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, IEnumerable<ResourceDescription>? manifestResources, CompilationTestData? testData, DiagnosticBag diagnostics, CancellationToken cancellationToken) { Debug.Assert(!IsSubmission || HasCodeToEmit() || (emitOptions == EmitOptions.Default && debugEntryPoint is null && sourceLinkStream is null && embeddedTexts is null && manifestResources is null && testData is null)); string? runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions, diagnostics); if (runtimeMDVersion == null) { return null; } var moduleProps = ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion); if (manifestResources == null) { manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>(); } PEModuleBuilder moduleBeingBuilt; if (_options.OutputKind.IsNetModule()) { moduleBeingBuilt = new PENetModuleBuilder( (SourceModuleSymbol)SourceModule, emitOptions, moduleProps, manifestResources); } else { var kind = _options.OutputKind.IsValid() ? _options.OutputKind : OutputKind.DynamicallyLinkedLibrary; moduleBeingBuilt = new PEAssemblyBuilder( SourceAssembly, emitOptions, kind, moduleProps, manifestResources); } if (debugEntryPoint != null) { moduleBeingBuilt.SetDebugEntryPoint(debugEntryPoint.GetSymbol(), diagnostics); } moduleBeingBuilt.SourceLinkStreamOpt = sourceLinkStream; if (embeddedTexts != null) { moduleBeingBuilt.EmbeddedTexts = embeddedTexts; } // testData is only passed when running tests. if (testData != null) { moduleBeingBuilt.SetMethodTestData(testData.Methods); testData.Module = moduleBeingBuilt; } return moduleBeingBuilt; } internal override bool CompileMethods( CommonPEModuleBuilder moduleBuilder, bool emittingPdb, bool emitMetadataOnly, bool emitTestCoverageData, DiagnosticBag diagnostics, Predicate<ISymbolInternal>? filterOpt, CancellationToken cancellationToken) { // The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that the emitter // does not attempt to emit if there are declaration errors (but we do insert all errors from method body binding...) PooledHashSet<int>? excludeDiagnostics = null; if (emitMetadataOnly) { excludeDiagnostics = PooledHashSet<int>.GetInstance(); excludeDiagnostics.Add((int)ErrorCode.ERR_ConcreteMissingBody); } bool hasDeclarationErrors = !FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, true, cancellationToken), excludeDiagnostics, cancellationToken); excludeDiagnostics?.Free(); // TODO (tomat): NoPIA: // EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(this) var moduleBeingBuilt = (PEModuleBuilder)moduleBuilder; if (emitMetadataOnly) { if (hasDeclarationErrors) { return false; } if (moduleBeingBuilt.SourceModule.HasBadAttributes) { // If there were errors but no declaration diagnostics, explicitly add a "Failed to emit module" error. diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((Cci.INamedEntity)moduleBeingBuilt).Name, new LocalizableResourceString(nameof(CodeAnalysisResources.ModuleHasInvalidAttributes), CodeAnalysisResources.ResourceManager, typeof(CodeAnalysisResources))); return false; } SynthesizedMetadataCompiler.ProcessSynthesizedMembers(this, moduleBeingBuilt, cancellationToken); } else { if ((emittingPdb || emitTestCoverageData) && !CreateDebugDocuments(moduleBeingBuilt.DebugDocumentsBuilder, moduleBeingBuilt.EmbeddedTexts, diagnostics)) { return false; } // Perform initial bind of method bodies in spite of earlier errors. This is the same // behavior as when calling GetDiagnostics() // Use a temporary bag so we don't have to refilter pre-existing diagnostics. DiagnosticBag? methodBodyDiagnosticBag = DiagnosticBag.GetInstance(); Debug.Assert(moduleBeingBuilt is object); MethodCompiler.CompileMethodBodies( this, moduleBeingBuilt, emittingPdb, emitTestCoverageData, hasDeclarationErrors, emitMethodBodies: true, diagnostics: new BindingDiagnosticBag(methodBodyDiagnosticBag), filterOpt: filterOpt, cancellationToken: cancellationToken); if (!hasDeclarationErrors && !CommonCompiler.HasUnsuppressableErrors(methodBodyDiagnosticBag)) { GenerateModuleInitializer(moduleBeingBuilt, methodBodyDiagnosticBag); } bool hasMethodBodyError = !FilterAndAppendAndFreeDiagnostics(diagnostics, ref methodBodyDiagnosticBag, cancellationToken); if (hasDeclarationErrors || hasMethodBodyError) { return false; } } return true; } private void GenerateModuleInitializer(PEModuleBuilder moduleBeingBuilt, DiagnosticBag methodBodyDiagnosticBag) { Debug.Assert(_declarationDiagnosticsFrozen); if (_moduleInitializerMethods is object) { var ilBuilder = new ILBuilder(moduleBeingBuilt, new LocalSlotManager(slotAllocator: null), OptimizationLevel.Release, areLocalsZeroed: false); foreach (MethodSymbol method in _moduleInitializerMethods.OrderBy<MethodSymbol>(LexicalOrderSymbolComparer.Instance)) { ilBuilder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); ilBuilder.EmitToken( moduleBeingBuilt.Translate(method, methodBodyDiagnosticBag, needDeclaration: true), CSharpSyntaxTree.Dummy.GetRoot(), methodBodyDiagnosticBag); } ilBuilder.EmitRet(isVoid: true); ilBuilder.Realize(); moduleBeingBuilt.RootModuleType.SetStaticConstructorBody(ilBuilder.RealizedIL); } } internal override bool GenerateResourcesAndDocumentationComments( CommonPEModuleBuilder moduleBuilder, Stream? xmlDocStream, Stream? win32Resources, bool useRawWin32Resources, string? outputNameOverride, DiagnosticBag diagnostics, CancellationToken cancellationToken) { // Use a temporary bag so we don't have to refilter pre-existing diagnostics. DiagnosticBag? resourceDiagnostics = DiagnosticBag.GetInstance(); SetupWin32Resources(moduleBuilder, win32Resources, useRawWin32Resources, resourceDiagnostics); ReportManifestResourceDuplicates( moduleBuilder.ManifestResources, SourceAssembly.Modules.Skip(1).Select(m => m.Name), //all modules except the first one AddedModulesResourceNames(resourceDiagnostics), resourceDiagnostics); if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref resourceDiagnostics, cancellationToken)) { return false; } cancellationToken.ThrowIfCancellationRequested(); // Use a temporary bag so we don't have to refilter pre-existing diagnostics. DiagnosticBag? xmlDiagnostics = DiagnosticBag.GetInstance(); string? assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, extension: null); DocumentationCommentCompiler.WriteDocumentationCommentXml(this, assemblyName, xmlDocStream, new BindingDiagnosticBag(xmlDiagnostics), cancellationToken); return FilterAndAppendAndFreeDiagnostics(diagnostics, ref xmlDiagnostics, cancellationToken); } private IEnumerable<string> AddedModulesResourceNames(DiagnosticBag diagnostics) { ImmutableArray<ModuleSymbol> modules = SourceAssembly.Modules; for (int i = 1; i < modules.Length; i++) { var m = (Symbols.Metadata.PE.PEModuleSymbol)modules[i]; ImmutableArray<EmbeddedResource> resources; try { resources = m.Module.GetEmbeddedResourcesOrThrow(); } catch (BadImageFormatException) { diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, m), NoLocation.Singleton); continue; } foreach (var resource in resources) { yield return resource.Name; } } } internal override EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken) { return EmitHelpers.EmitDifference( this, baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData, cancellationToken); } internal string? GetRuntimeMetadataVersion(EmitOptions emitOptions, DiagnosticBag diagnostics) { string? runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions); if (runtimeMDVersion != null) { return runtimeMDVersion; } DiagnosticBag? runtimeMDVersionDiagnostics = DiagnosticBag.GetInstance(); runtimeMDVersionDiagnostics.Add(ErrorCode.WRN_NoRuntimeMetadataVersion, NoLocation.Singleton); if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref runtimeMDVersionDiagnostics, CancellationToken.None)) { return null; } return string.Empty; //prevent emitter from crashing. } private string? GetRuntimeMetadataVersion(EmitOptions emitOptions) { var corAssembly = Assembly.CorLibrary as Symbols.Metadata.PE.PEAssemblySymbol; if (corAssembly is object) { return corAssembly.Assembly.ManifestModule.MetadataVersion; } return emitOptions.RuntimeMetadataVersion; } internal override void AddDebugSourceDocumentsForChecksumDirectives( DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics) { var checksumDirectives = tree.GetRoot().GetDirectives(d => d.Kind() == SyntaxKind.PragmaChecksumDirectiveTrivia && !d.ContainsDiagnostics); foreach (var directive in checksumDirectives) { var checksumDirective = (PragmaChecksumDirectiveTriviaSyntax)directive; var path = checksumDirective.File.ValueText; var checksumText = checksumDirective.Bytes.ValueText; var normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(path, basePath: tree.FilePath); var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath); // duplicate checksum pragmas are valid as long as values match // if we have seen this document already, check for matching values. if (existingDoc != null) { // pragma matches a file path on an actual tree. // Dev12 compiler just ignores the pragma in this case which means that // checksum of the actual tree always wins and no warning is given. // We will continue doing the same. if (existingDoc.IsComputedChecksum) { continue; } var sourceInfo = existingDoc.GetSourceInfo(); if (ChecksumMatches(checksumText, sourceInfo.Checksum)) { var guid = Guid.Parse(checksumDirective.Guid.ValueText); if (guid == sourceInfo.ChecksumAlgorithmId) { // all parts match, nothing to do continue; } } // did not match to an existing document // produce a warning and ignore the pragma diagnostics.Add(ErrorCode.WRN_ConflictingChecksum, new SourceLocation(checksumDirective), path); } else { var newDocument = new Cci.DebugSourceDocument( normalizedPath, Cci.DebugSourceDocument.CorSymLanguageTypeCSharp, MakeChecksumBytes(checksumText), Guid.Parse(checksumDirective.Guid.ValueText)); documentsBuilder.AddDebugDocument(newDocument); } } } private static bool ChecksumMatches(string bytesText, ImmutableArray<byte> bytes) { if (bytesText.Length != bytes.Length * 2) { return false; } for (int i = 0, len = bytesText.Length / 2; i < len; i++) { // 1A in text becomes 0x1A var b = SyntaxFacts.HexValue(bytesText[i * 2]) * 16 + SyntaxFacts.HexValue(bytesText[i * 2 + 1]); if (b != bytes[i]) { return false; } } return true; } private static ImmutableArray<byte> MakeChecksumBytes(string bytesText) { int length = bytesText.Length / 2; var builder = ArrayBuilder<byte>.GetInstance(length); for (int i = 0; i < length; i++) { // 1A in text becomes 0x1A var b = SyntaxFacts.HexValue(bytesText[i * 2]) * 16 + SyntaxFacts.HexValue(bytesText[i * 2 + 1]); builder.Add((byte)b); } return builder.ToImmutableAndFree(); } internal override Guid DebugSourceDocumentLanguageId => Cci.DebugSourceDocument.CorSymLanguageTypeCSharp; internal override bool HasCodeToEmit() { foreach (var syntaxTree in this.SyntaxTrees) { var unit = syntaxTree.GetCompilationUnitRoot(); if (unit.Members.Count > 0) { return true; } } return false; } #endregion #region Common Members protected override Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences) { return WithReferences(newReferences); } protected override Compilation CommonWithAssemblyName(string? assemblyName) { return WithAssemblyName(assemblyName); } protected override IAssemblySymbol CommonAssembly { get { return this.Assembly.GetPublicSymbol(); } } protected override INamespaceSymbol CommonGlobalNamespace { get { return this.GlobalNamespace.GetPublicSymbol(); } } protected override CompilationOptions CommonOptions { get { return _options; } } protected override SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility) { return this.GetSemanticModel((SyntaxTree)syntaxTree, ignoreAccessibility); } protected override ImmutableArray<SyntaxTree> CommonSyntaxTrees { get { return this.SyntaxTrees; } } protected override Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees) { return this.AddSyntaxTrees(trees); } protected override Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees) { return this.RemoveSyntaxTrees(trees); } protected override Compilation CommonRemoveAllSyntaxTrees() { return this.RemoveAllSyntaxTrees(); } protected override Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree? newTree) { return this.ReplaceSyntaxTree(oldTree, newTree); } protected override Compilation CommonWithOptions(CompilationOptions options) { return this.WithOptions((CSharpCompilationOptions)options); } protected override Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info) { return this.WithScriptCompilationInfo((CSharpScriptCompilationInfo?)info); } protected override bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree) { return this.ContainsSyntaxTree(syntaxTree); } protected override ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference) { return this.GetAssemblyOrModuleSymbol(reference).GetPublicSymbol(); } protected override Compilation CommonClone() { return this.Clone(); } protected override IModuleSymbol CommonSourceModule { get { return this.SourceModule.GetPublicSymbol(); } } private protected override INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType) { return this.GetSpecialType(specialType); } protected override INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol) { return this.GetCompilationNamespace(namespaceSymbol).GetPublicSymbol(); } protected override INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName) { return this.GetTypeByMetadataName(metadataName).GetPublicSymbol(); } protected override INamedTypeSymbol? CommonScriptClass { get { return this.ScriptClass.GetPublicSymbol(); } } protected override IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, CodeAnalysis.NullableAnnotation elementNullableAnnotation) { return CreateArrayTypeSymbol(elementType.EnsureCSharpSymbolOrNull(nameof(elementType)), rank, elementNullableAnnotation.ToInternalAnnotation()).GetPublicSymbol(); } protected override IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType) { return CreatePointerTypeSymbol(elementType.EnsureCSharpSymbolOrNull(nameof(elementType)), elementType.NullableAnnotation.ToInternalAnnotation()).GetPublicSymbol(); } protected override IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol( ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, SignatureCallingConvention callingConvention, ImmutableArray<INamedTypeSymbol> callingConventionTypes) { if (returnType is null) { throw new ArgumentNullException(nameof(returnType)); } if (parameterTypes.IsDefault) { throw new ArgumentNullException(nameof(parameterTypes)); } for (int i = 0; i < parameterTypes.Length; i++) { if (parameterTypes[i] is null) { throw new ArgumentNullException($"{nameof(parameterTypes)}[{i}]"); } } if (parameterRefKinds.IsDefault) { throw new ArgumentNullException(nameof(parameterRefKinds)); } if (parameterRefKinds.Length != parameterTypes.Length) { // Given {0} parameter types and {1} parameter ref kinds. These must be the same. throw new ArgumentException(string.Format(CSharpResources.NotSameNumberParameterTypesAndRefKinds, parameterTypes.Length, parameterRefKinds.Length)); } if (returnRefKind == RefKind.Out) { //'RefKind.Out' is not a valid ref kind for a return type. throw new ArgumentException(CSharpResources.OutIsNotValidForReturn); } if (callingConvention != SignatureCallingConvention.Unmanaged && !callingConventionTypes.IsDefaultOrEmpty) { throw new ArgumentException(string.Format(CSharpResources.CallingConventionTypesRequireUnmanaged, nameof(callingConventionTypes), nameof(callingConvention))); } if (!callingConvention.IsValid()) { throw new ArgumentOutOfRangeException(nameof(callingConvention)); } var returnTypeWithAnnotations = TypeWithAnnotations.Create(returnType.EnsureCSharpSymbolOrNull(nameof(returnType)), returnType.NullableAnnotation.ToInternalAnnotation()); var parameterTypesWithAnnotations = parameterTypes.SelectAsArray( type => TypeWithAnnotations.Create(type.EnsureCSharpSymbolOrNull(nameof(parameterTypes)), type.NullableAnnotation.ToInternalAnnotation())); var internalCallingConvention = callingConvention.FromSignatureConvention(); var conventionModifiers = internalCallingConvention == CallingConvention.Unmanaged && !callingConventionTypes.IsDefaultOrEmpty ? callingConventionTypes.SelectAsArray((type, i, @this) => getCustomModifierForType(type, @this, i), this) : ImmutableArray<CustomModifier>.Empty; return FunctionPointerTypeSymbol.CreateFromParts( internalCallingConvention, conventionModifiers, returnTypeWithAnnotations, returnRefKind: returnRefKind, parameterTypes: parameterTypesWithAnnotations, parameterRefKinds: parameterRefKinds, compilation: this).GetPublicSymbol(); static CustomModifier getCustomModifierForType(INamedTypeSymbol type, CSharpCompilation @this, int index) { if (type is null) { throw new ArgumentNullException($"{nameof(callingConventionTypes)}[{index}]"); } var internalType = type.EnsureCSharpSymbolOrNull($"{nameof(callingConventionTypes)}[{index}]"); if (!FunctionPointerTypeSymbol.IsCallingConventionModifier(internalType) || @this.Assembly.CorLibrary != internalType.ContainingAssembly) { throw new ArgumentException(string.Format(CSharpResources.CallingConventionTypeIsInvalid, type.ToDisplayString())); } return CSharpCustomModifier.CreateOptional(internalType); } } protected override INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed) { return CreateNativeIntegerTypeSymbol(signed).GetPublicSymbol(); } internal new NamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed) { return GetSpecialType(signed ? SpecialType.System_IntPtr : SpecialType.System_UIntPtr).AsNativeInteger(); } protected override INamedTypeSymbol CommonCreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<CodeAnalysis.NullableAnnotation> elementNullableAnnotations) { var typesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(elementTypes.Length); for (int i = 0; i < elementTypes.Length; i++) { ITypeSymbol typeSymbol = elementTypes[i]; var elementType = typeSymbol.EnsureCSharpSymbolOrNull($"{nameof(elementTypes)}[{i}]"); var annotation = (elementNullableAnnotations.IsDefault ? typeSymbol.NullableAnnotation : elementNullableAnnotations[i]).ToInternalAnnotation(); typesBuilder.Add(TypeWithAnnotations.Create(elementType, annotation)); } return NamedTypeSymbol.CreateTuple( locationOpt: null, // no location for the type declaration elementTypesWithAnnotations: typesBuilder.ToImmutableAndFree(), elementLocations: elementLocations, elementNames: elementNames, compilation: this, shouldCheckConstraints: false, includeNullability: false, errorPositions: default).GetPublicSymbol(); } protected override INamedTypeSymbol CommonCreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<CodeAnalysis.NullableAnnotation> elementNullableAnnotations) { NamedTypeSymbol csharpUnderlyingTuple = underlyingType.EnsureCSharpSymbolOrNull(nameof(underlyingType)); if (!csharpUnderlyingTuple.IsTupleTypeOfCardinality(out int cardinality)) { throw new ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, nameof(underlyingType)); } elementNames = CheckTupleElementNames(cardinality, elementNames); CheckTupleElementLocations(cardinality, elementLocations); CheckTupleElementNullableAnnotations(cardinality, elementNullableAnnotations); var tupleType = NamedTypeSymbol.CreateTuple( csharpUnderlyingTuple, elementNames, elementLocations: elementLocations!); if (!elementNullableAnnotations.IsDefault) { tupleType = tupleType.WithElementTypes( tupleType.TupleElementTypesWithAnnotations.ZipAsArray( elementNullableAnnotations, (t, a) => TypeWithAnnotations.Create(t.Type, a.ToInternalAnnotation()))); } return tupleType.GetPublicSymbol(); } protected override INamedTypeSymbol CommonCreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<Location> memberLocations, ImmutableArray<bool> memberIsReadOnly, ImmutableArray<CodeAnalysis.NullableAnnotation> memberNullableAnnotations) { for (int i = 0, n = memberTypes.Length; i < n; i++) { memberTypes[i].EnsureCSharpSymbolOrNull($"{nameof(memberTypes)}[{i}]"); } if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Any(v => !v)) { throw new ArgumentException($"Non-ReadOnly members are not supported in C# anonymous types."); } var fields = ArrayBuilder<AnonymousTypeField>.GetInstance(); for (int i = 0, n = memberTypes.Length; i < n; i++) { var type = memberTypes[i].GetSymbol(); var name = memberNames[i]; var location = memberLocations.IsDefault ? Location.None : memberLocations[i]; var nullableAnnotation = memberNullableAnnotations.IsDefault ? NullableAnnotation.Oblivious : memberNullableAnnotations[i].ToInternalAnnotation(); fields.Add(new AnonymousTypeField(name, location, TypeWithAnnotations.Create(type, nullableAnnotation))); } var descriptor = new AnonymousTypeDescriptor(fields.ToImmutableAndFree(), Location.None); return this.AnonymousTypeManager.ConstructAnonymousTypeSymbol(descriptor).GetPublicSymbol(); } protected override ITypeSymbol CommonDynamicType { get { return DynamicType.GetPublicSymbol(); } } protected override INamedTypeSymbol CommonObjectType { get { return this.ObjectType.GetPublicSymbol(); } } protected override IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken) { return this.GetEntryPoint(cancellationToken).GetPublicSymbol(); } internal override int CompareSourceLocations(Location loc1, Location loc2) { Debug.Assert(loc1.IsInSource); Debug.Assert(loc2.IsInSource); var comparison = CompareSyntaxTreeOrdering(loc1.SourceTree!, loc2.SourceTree!); if (comparison != 0) { return comparison; } return loc1.SourceSpan.Start - loc2.SourceSpan.Start; } internal override int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2) { var comparison = CompareSyntaxTreeOrdering(loc1.SyntaxTree, loc2.SyntaxTree); if (comparison != 0) { return comparison; } return loc1.Span.Start - loc2.Span.Start; } internal override int CompareSourceLocations(SyntaxNode loc1, SyntaxNode loc2) { var comparison = CompareSyntaxTreeOrdering(loc1.SyntaxTree, loc2.SyntaxTree); if (comparison != 0) { return comparison; } return loc1.Span.Start - loc2.Span.Start; } /// <summary> /// Return true if there is a source declaration symbol name that meets given predicate. /// </summary> public override bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return DeclarationTable.ContainsName(this.MergedRootDeclaration, predicate, filter, cancellationToken); } /// <summary> /// Return source declaration symbols whose name meets given predicate. /// </summary> public override IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (predicate == null) { throw new ArgumentNullException(nameof(predicate)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return new PredicateSymbolSearcher(this, filter, predicate, cancellationToken).GetSymbolsWithName().GetPublicSymbols()!; } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Return true if there is a source declaration symbol name that matches the provided name. /// This will be faster than <see cref="ContainsSymbolsWithName(Func{string, bool}, SymbolFilter, CancellationToken)"/> /// when predicate is just a simple string check. /// </summary> public override bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return DeclarationTable.ContainsName(this.MergedRootDeclaration, name, filter, cancellationToken); } /// <summary> /// Return source declaration symbols whose name matches the provided name. This will be /// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter, /// CancellationToken)"/> when predicate is just a simple string check. <paramref /// name="name"/> is case sensitive. /// </summary> public override IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { return GetSymbolsWithNameCore(name, filter, cancellationToken).GetPublicSymbols()!; } internal IEnumerable<Symbol> GetSymbolsWithNameCore(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (filter == SymbolFilter.None) { throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter)); } return new NameSymbolSearcher(this, filter, name, cancellationToken).GetSymbolsWithName(); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters #endregion /// <summary> /// Returns if the compilation has all of the members necessary to emit metadata about /// dynamic types. /// </summary> /// <returns></returns> internal bool HasDynamicEmitAttributes(BindingDiagnosticBag diagnostics, Location location) { return Binder.GetWellKnownTypeMember(this, WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor, diagnostics, location) is object && Binder.GetWellKnownTypeMember(this, WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags, diagnostics, location) is object; } internal bool HasTupleNamesAttributes(BindingDiagnosticBag diagnostics, Location location) => Binder.GetWellKnownTypeMember(this, WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames, diagnostics, location) is object; /// <summary> /// Returns whether the compilation has the Boolean type and if it's good. /// </summary> /// <returns>Returns true if Boolean is present and healthy.</returns> internal bool CanEmitBoolean() => CanEmitSpecialType(SpecialType.System_Boolean); internal bool CanEmitSpecialType(SpecialType type) { var typeSymbol = GetSpecialType(type); var diagnostic = typeSymbol.GetUseSiteInfo().DiagnosticInfo; return (diagnostic == null) || (diagnostic.Severity != DiagnosticSeverity.Error); } internal bool EmitNullablePublicOnly { get { if (!_lazyEmitNullablePublicOnly.HasValue()) { bool value = SyntaxTrees.FirstOrDefault()?.Options?.Features?.ContainsKey("nullablePublicOnly") == true; _lazyEmitNullablePublicOnly = value.ToThreeState(); } return _lazyEmitNullablePublicOnly.Value(); } } internal bool ShouldEmitNullableAttributes(Symbol symbol) { RoslynDebug.Assert(symbol is object); Debug.Assert(symbol.IsDefinition); if (symbol.ContainingModule != SourceModule) { return false; } if (!EmitNullablePublicOnly) { return true; } // For symbols that do not have explicit accessibility in metadata, // use the accessibility of the container. symbol = getExplicitAccessibilitySymbol(symbol); if (!AccessCheck.IsEffectivelyPublicOrInternal(symbol, out bool isInternal)) { return false; } return !isInternal || SourceAssembly.InternalsAreVisible; static Symbol getExplicitAccessibilitySymbol(Symbol symbol) { while (true) { switch (symbol.Kind) { case SymbolKind.Parameter: case SymbolKind.TypeParameter: case SymbolKind.Property: case SymbolKind.Event: symbol = symbol.ContainingSymbol; break; default: return symbol; } } } } internal override AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter) { Func<SyntaxNode, SyntaxKind> getKind = node => node.Kind(); Func<SyntaxTrivia, bool> isComment = trivia => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia; return new AnalyzerDriver<SyntaxKind>(analyzers, getKind, analyzerManager, severityFilter, isComment); } internal void SymbolDeclaredEvent(Symbol symbol) { EventQueue?.TryEnqueue(new SymbolDeclaredCompilationEvent(this, symbol.GetPublicSymbol())); } internal override void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder) { // LanguageVersion should already be mapped to a specific version Debug.Assert(LanguageVersion == LanguageVersion.MapSpecifiedToEffectiveVersion()); WriteValue(CompilationOptionNames.LanguageVersion, LanguageVersion.ToDisplayString()); if (Options.CheckOverflow) { WriteValue(CompilationOptionNames.Checked, Options.CheckOverflow.ToString()); } if (Options.NullableContextOptions != NullableContextOptions.Disable) { WriteValue(CompilationOptionNames.Nullable, Options.NullableContextOptions.ToString()); } if (Options.AllowUnsafe) { WriteValue(CompilationOptionNames.Unsafe, Options.AllowUnsafe.ToString()); } var preprocessorSymbols = GetPreprocessorSymbols(); if (preprocessorSymbols.Any()) { WriteValue(CompilationOptionNames.Define, string.Join(",", preprocessorSymbols)); } void WriteValue(string key, string value) { builder.WriteUTF8(key); builder.WriteByte(0); builder.WriteUTF8(value); builder.WriteByte(0); } } private ImmutableArray<string> GetPreprocessorSymbols() { CSharpSyntaxTree? firstTree = (CSharpSyntaxTree?)SyntaxTrees.FirstOrDefault(); if (firstTree is null) { return ImmutableArray<string>.Empty; } return firstTree.Options.PreprocessorSymbolNames.ToImmutableArray(); } /// <summary> /// Determine if enum arrays can be initialized using block initialization. /// </summary> /// <returns>True if it's safe to use block initialization for enum arrays.</returns> /// <remarks> /// In NetFx 4.0, block array initializers do not work on all combinations of {32/64 X Debug/Retail} when array elements are enums. /// This is fixed in 4.5 thus enabling block array initialization for a very common case. /// We look for the presence of <see cref="System.Runtime.GCLatencyMode.SustainedLowLatency"/> which was introduced in .NET Framework 4.5 /// </remarks> internal bool EnableEnumArrayBlockInitialization { get { var sustainedLowLatency = GetWellKnownTypeMember(WellKnownMember.System_Runtime_GCLatencyMode__SustainedLowLatency); return sustainedLowLatency != null && sustainedLowLatency.ContainingAssembly == Assembly.CorLibrary; } } private abstract class AbstractSymbolSearcher { private readonly PooledDictionary<Declaration, NamespaceOrTypeSymbol> _cache; private readonly CSharpCompilation _compilation; private readonly bool _includeNamespace; private readonly bool _includeType; private readonly bool _includeMember; private readonly CancellationToken _cancellationToken; protected AbstractSymbolSearcher( CSharpCompilation compilation, SymbolFilter filter, CancellationToken cancellationToken) { _cache = PooledDictionary<Declaration, NamespaceOrTypeSymbol>.GetInstance(); _compilation = compilation; _includeNamespace = (filter & SymbolFilter.Namespace) == SymbolFilter.Namespace; _includeType = (filter & SymbolFilter.Type) == SymbolFilter.Type; _includeMember = (filter & SymbolFilter.Member) == SymbolFilter.Member; _cancellationToken = cancellationToken; } protected abstract bool Matches(string name); protected abstract bool ShouldCheckTypeForMembers(MergedTypeDeclaration current); public IEnumerable<Symbol> GetSymbolsWithName() { var result = new HashSet<Symbol>(); var spine = ArrayBuilder<MergedNamespaceOrTypeDeclaration>.GetInstance(); AppendSymbolsWithName(spine, _compilation.MergedRootDeclaration, result); spine.Free(); _cache.Free(); return result; } private void AppendSymbolsWithName( ArrayBuilder<MergedNamespaceOrTypeDeclaration> spine, MergedNamespaceOrTypeDeclaration current, HashSet<Symbol> set) { if (current.Kind == DeclarationKind.Namespace) { if (_includeNamespace && Matches(current.Name)) { var container = GetSpineSymbol(spine); var symbol = GetSymbol(container, current); if (symbol != null) { set.Add(symbol); } } } else { if (_includeType && Matches(current.Name)) { var container = GetSpineSymbol(spine); var symbol = GetSymbol(container, current); if (symbol != null) { set.Add(symbol); } } if (_includeMember) { var typeDeclaration = (MergedTypeDeclaration)current; if (ShouldCheckTypeForMembers(typeDeclaration)) { AppendMemberSymbolsWithName(spine, typeDeclaration, set); } } } spine.Add(current); foreach (var child in current.Children) { if (child is MergedNamespaceOrTypeDeclaration mergedNamespaceOrType) { if (_includeMember || _includeType || child.Kind == DeclarationKind.Namespace) { AppendSymbolsWithName(spine, mergedNamespaceOrType, set); } } } // pop last one spine.RemoveAt(spine.Count - 1); } private void AppendMemberSymbolsWithName( ArrayBuilder<MergedNamespaceOrTypeDeclaration> spine, MergedTypeDeclaration current, HashSet<Symbol> set) { _cancellationToken.ThrowIfCancellationRequested(); spine.Add(current); var container = GetSpineSymbol(spine); if (container != null) { foreach (var member in container.GetMembers()) { if (!member.IsTypeOrTypeAlias() && (member.CanBeReferencedByName || member.IsExplicitInterfaceImplementation() || member.IsIndexer()) && Matches(member.Name)) { set.Add(member); } } } spine.RemoveAt(spine.Count - 1); } protected NamespaceOrTypeSymbol? GetSpineSymbol(ArrayBuilder<MergedNamespaceOrTypeDeclaration> spine) { if (spine.Count == 0) { return null; } var symbol = GetCachedSymbol(spine[spine.Count - 1]); if (symbol != null) { return symbol; } NamespaceOrTypeSymbol? current = _compilation.GlobalNamespace; for (var i = 1; i < spine.Count; i++) { current = GetSymbol(current, spine[i]); } return current; } private NamespaceOrTypeSymbol? GetCachedSymbol(MergedNamespaceOrTypeDeclaration declaration) => _cache.TryGetValue(declaration, out NamespaceOrTypeSymbol? symbol) ? symbol : null; private NamespaceOrTypeSymbol? GetSymbol(NamespaceOrTypeSymbol? container, MergedNamespaceOrTypeDeclaration declaration) { if (container == null) { return _compilation.GlobalNamespace; } if (declaration.Kind == DeclarationKind.Namespace) { AddCache(container.GetMembers(declaration.Name).OfType<NamespaceOrTypeSymbol>()); } else { AddCache(container.GetTypeMembers(declaration.Name)); } return GetCachedSymbol(declaration); } private void AddCache(IEnumerable<NamespaceOrTypeSymbol> symbols) { foreach (var symbol in symbols) { var mergedNamespace = symbol as MergedNamespaceSymbol; if (mergedNamespace != null) { _cache[mergedNamespace.ConstituentNamespaces.OfType<SourceNamespaceSymbol>().First().MergedDeclaration] = symbol; continue; } var sourceNamespace = symbol as SourceNamespaceSymbol; if (sourceNamespace != null) { _cache[sourceNamespace.MergedDeclaration] = sourceNamespace; continue; } var sourceType = symbol as SourceMemberContainerTypeSymbol; if (sourceType is object) { _cache[sourceType.MergedDeclaration] = sourceType; } } } } private class PredicateSymbolSearcher : AbstractSymbolSearcher { private readonly Func<string, bool> _predicate; public PredicateSymbolSearcher( CSharpCompilation compilation, SymbolFilter filter, Func<string, bool> predicate, CancellationToken cancellationToken) : base(compilation, filter, cancellationToken) { _predicate = predicate; } protected override bool ShouldCheckTypeForMembers(MergedTypeDeclaration current) { // Note: this preserves the behavior the compiler has always had when a predicate // is passed in. We could potentially be smarter by checking the predicate // against the list of member names in the type declaration first. return true; } protected override bool Matches(string name) => _predicate(name); } private class NameSymbolSearcher : AbstractSymbolSearcher { private readonly string _name; public NameSymbolSearcher( CSharpCompilation compilation, SymbolFilter filter, string name, CancellationToken cancellationToken) : base(compilation, filter, cancellationToken) { _name = name; } protected override bool ShouldCheckTypeForMembers(MergedTypeDeclaration current) { foreach (SingleTypeDeclaration typeDecl in current.Declarations) { if (typeDecl.MemberNames.ContainsKey(_name)) { return true; } } return false; } protected override bool Matches(string name) => _name == name; } } }
1
dotnet/roslyn
56,218
Eliminate 75GB allocations during binding in a performance trace
Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
sharwell
"2021-09-07T16:51:03Z"
"2021-09-09T22:25:38Z"
e3e8c6e5196d73d1b7582d40a3c48a22c68e6441
ba2203796b7906d6f53b53bc6fa93f1708e11944
Eliminate 75GB allocations during binding in a performance trace. Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
./src/Compilers/CSharp/Portable/Symbols/NamespaceOrTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents either a namespace or a type. /// </summary> internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 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. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Only the compiler can create new instances. internal NamespaceOrTypeSymbol() { } /// <summary> /// Returns true if this symbol is a namespace. If it is not a namespace, it must be a type. /// </summary> public bool IsNamespace { get { return Kind == SymbolKind.Namespace; } } /// <summary> /// Returns true if this symbols is a type. Equivalent to !IsNamespace. /// </summary> public bool IsType { get { return !IsNamespace; } } /// <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> /// <returns> /// Always returns false. /// </returns> public sealed 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> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsOverride { get { return false; } } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// "extern" modifier. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsExtern { get { return false; } } /// <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 ImmutableArray<Symbol> GetMembers(); /// <summary> /// Get all the members of this symbol. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </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> internal virtual ImmutableArray<Symbol> GetMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetMembers().ConditionallyDeOrder(); } /// <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 ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// Get all the members of this symbol that are types. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </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> internal virtual ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetTypeMembers().ConditionallyDeOrder(); } /// <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 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 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 IEnumerable 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 IEnumerable. Never returns null.</returns> public virtual ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { // default implementation does a post-filter. We can override this if its a performance burden, but // experience is that it won't be. return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(TypeDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(DelegateDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol of given name, arity and kind. If a tree and syntax are provided, restrict the results /// to those that are declared within the given syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember( string name, int arity, SyntaxKind kind, CSharpSyntaxNode syntax) { TypeKind typeKind = kind.ToDeclarationKind().ToTypeKind(); foreach (var member in GetTypeMembers(name, arity)) { var memberT = member as SourceNamedTypeSymbol; if ((object?)memberT != null && memberT.TypeKind == typeKind) { if (syntax != null) { foreach (var loc in memberT.Locations) { if (loc.IsInSource && loc.SourceTree == syntax.SyntaxTree && syntax.Span.Contains(loc.SourceSpan)) { return memberT; } } } else { return memberT; } } } // None found. return null; } /// <summary> /// Lookup an immediately nested type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedTypeName"> /// Simple type name, possibly with generic name mangling. /// </param> /// <returns> /// Symbol for the type, or MissingMetadataSymbol if the type isn't found. /// </returns> internal virtual NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName) { Debug.Assert(!emittedTypeName.IsNull); NamespaceOrTypeSymbol scope = this; if (scope.Kind == SymbolKind.ErrorType) { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } NamedTypeSymbol? namedType = null; ImmutableArray<NamedTypeSymbol> namespaceOrTypeMembers; bool isTopLevel = scope.IsNamespace; Debug.Assert(!isTopLevel || scope.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) == emittedTypeName.NamespaceName); if (emittedTypeName.IsMangled) { Debug.Assert(!emittedTypeName.UnmangledTypeName.Equals(emittedTypeName.TypeName) && emittedTypeName.InferredArity > 0); if (emittedTypeName.ForcedArity == -1 || emittedTypeName.ForcedArity == emittedTypeName.InferredArity) { // Let's handle mangling case first. namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.UnmangledTypeName); foreach (var named in namespaceOrTypeMembers) { if (emittedTypeName.InferredArity == named.Arity && named.MangleName) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } } } else { Debug.Assert(ReferenceEquals(emittedTypeName.UnmangledTypeName, emittedTypeName.TypeName) && emittedTypeName.InferredArity == 0); } // Now try lookup without removing generic arity mangling. int forcedArity = emittedTypeName.ForcedArity; if (emittedTypeName.UseCLSCompliantNameArityEncoding) { // Only types with arity 0 are acceptable, we already examined types with mangled names. if (emittedTypeName.InferredArity > 0) { goto Done; } else if (forcedArity == -1) { forcedArity = 0; } else if (forcedArity != 0) { goto Done; } else { Debug.Assert(forcedArity == emittedTypeName.InferredArity); } } namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.TypeName); foreach (var named in namespaceOrTypeMembers) { if (!named.MangleName && (forcedArity == -1 || forcedArity == named.Arity)) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } Done: if ((object?)namedType == null) { if (isTopLevel) { return new MissingMetadataTypeSymbol.TopLevel(scope.ContainingModule, ref emittedTypeName); } else { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } } return namedType; } /// <summary> /// Finds types or namespaces described by a qualified name. /// </summary> /// <param name="qualifiedName">Sequence of simple plain names.</param> /// <returns> /// A set of namespace or type symbols with given qualified name (might comprise of types with multiple generic arities), /// or an empty set if the member can't be found (the qualified name is ambiguous or the symbol doesn't exist). /// </returns> /// <remarks> /// "C.D" matches C.D, C{T}.D, C{S,T}.D{U}, etc. /// </remarks> internal IEnumerable<NamespaceOrTypeSymbol>? GetNamespaceOrTypeByQualifiedName(IEnumerable<string> qualifiedName) { NamespaceOrTypeSymbol namespaceOrType = this; IEnumerable<NamespaceOrTypeSymbol>? symbols = null; foreach (string name in qualifiedName) { if (symbols != null) { // there might be multiple types of different arity, prefer a non-generic type: namespaceOrType = symbols.OfMinimalArity(); if ((object)namespaceOrType == null) { return SpecializedCollections.EmptyEnumerable<NamespaceOrTypeSymbol>(); } } symbols = namespaceOrType.GetMembers(name).OfType<NamespaceOrTypeSymbol>(); } return symbols; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Symbols; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents either a namespace or a type. /// </summary> internal abstract class NamespaceOrTypeSymbol : Symbol, INamespaceOrTypeSymbolInternal { // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // 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. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Only the compiler can create new instances. internal NamespaceOrTypeSymbol() { } /// <summary> /// Returns true if this symbol is a namespace. If it is not a namespace, it must be a type. /// </summary> public bool IsNamespace { get { return Kind == SymbolKind.Namespace; } } /// <summary> /// Returns true if this symbols is a type. Equivalent to !IsNamespace. /// </summary> public bool IsType { get { return !IsNamespace; } } /// <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> /// <returns> /// Always returns false. /// </returns> public sealed 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> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsOverride { get { return false; } } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// "extern" modifier. /// </summary> /// <returns> /// Always returns false. /// </returns> public sealed override bool IsExtern { get { return false; } } /// <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 ImmutableArray<Symbol> GetMembers(); /// <summary> /// Get all the members of this symbol. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </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> internal virtual ImmutableArray<Symbol> GetMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetMembers().ConditionallyDeOrder(); } /// <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 ImmutableArray<Symbol> GetMembers(string name); /// <summary> /// Get all the members of this symbol that are types. The members may not be in a particular order, and the order /// may not be stable from call-to-call. /// </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> internal virtual ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { // Default implementation is to use ordered version. When performance indicates, we specialize to have // separate implementation. return GetTypeMembers().ConditionallyDeOrder(); } /// <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 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 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 IEnumerable 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 IEnumerable. Never returns null.</returns> public virtual ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { // default implementation does a post-filter. We can override this if its a performance burden, but // experience is that it won't be. return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(TypeDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol for the given declaration syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember(DelegateDeclarationSyntax syntax) { return GetSourceTypeMember(syntax.Identifier.ValueText, syntax.Arity, syntax.Kind(), syntax); } /// <summary> /// Get a source type symbol of given name, arity and kind. If a tree and syntax are provided, restrict the results /// to those that are declared within the given syntax. /// </summary> /// <returns>Null if there is no matching declaration.</returns> internal SourceNamedTypeSymbol? GetSourceTypeMember( string name, int arity, SyntaxKind kind, CSharpSyntaxNode syntax) { TypeKind typeKind = kind.ToDeclarationKind().ToTypeKind(); foreach (var member in GetTypeMembers(name, arity)) { var memberT = member as SourceNamedTypeSymbol; if ((object?)memberT != null && memberT.TypeKind == typeKind) { if (syntax != null) { // PERF: Avoid accessing Locations for performance, but assert that the alternative approach is // equivalent. Debug.Assert(memberT.MergedDeclaration.Declarations.SelectAsArray(decl => decl.NameLocation).SequenceEqual(memberT.Locations)); foreach (var declaration in memberT.MergedDeclaration.Declarations) { var loc = declaration.NameLocation; if (loc.IsInSource && loc.SourceTree == syntax.SyntaxTree && syntax.Span.Contains(loc.SourceSpan)) { return memberT; } } } else { return memberT; } } } // None found. return null; } /// <summary> /// Lookup an immediately nested type referenced from metadata, names should be /// compared case-sensitively. /// </summary> /// <param name="emittedTypeName"> /// Simple type name, possibly with generic name mangling. /// </param> /// <returns> /// Symbol for the type, or MissingMetadataSymbol if the type isn't found. /// </returns> internal virtual NamedTypeSymbol LookupMetadataType(ref MetadataTypeName emittedTypeName) { Debug.Assert(!emittedTypeName.IsNull); NamespaceOrTypeSymbol scope = this; if (scope.Kind == SymbolKind.ErrorType) { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } NamedTypeSymbol? namedType = null; ImmutableArray<NamedTypeSymbol> namespaceOrTypeMembers; bool isTopLevel = scope.IsNamespace; Debug.Assert(!isTopLevel || scope.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat) == emittedTypeName.NamespaceName); if (emittedTypeName.IsMangled) { Debug.Assert(!emittedTypeName.UnmangledTypeName.Equals(emittedTypeName.TypeName) && emittedTypeName.InferredArity > 0); if (emittedTypeName.ForcedArity == -1 || emittedTypeName.ForcedArity == emittedTypeName.InferredArity) { // Let's handle mangling case first. namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.UnmangledTypeName); foreach (var named in namespaceOrTypeMembers) { if (emittedTypeName.InferredArity == named.Arity && named.MangleName) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } } } else { Debug.Assert(ReferenceEquals(emittedTypeName.UnmangledTypeName, emittedTypeName.TypeName) && emittedTypeName.InferredArity == 0); } // Now try lookup without removing generic arity mangling. int forcedArity = emittedTypeName.ForcedArity; if (emittedTypeName.UseCLSCompliantNameArityEncoding) { // Only types with arity 0 are acceptable, we already examined types with mangled names. if (emittedTypeName.InferredArity > 0) { goto Done; } else if (forcedArity == -1) { forcedArity = 0; } else if (forcedArity != 0) { goto Done; } else { Debug.Assert(forcedArity == emittedTypeName.InferredArity); } } namespaceOrTypeMembers = scope.GetTypeMembers(emittedTypeName.TypeName); foreach (var named in namespaceOrTypeMembers) { if (!named.MangleName && (forcedArity == -1 || forcedArity == named.Arity)) { if ((object?)namedType != null) { namedType = null; break; } namedType = named; } } Done: if ((object?)namedType == null) { if (isTopLevel) { return new MissingMetadataTypeSymbol.TopLevel(scope.ContainingModule, ref emittedTypeName); } else { return new MissingMetadataTypeSymbol.Nested((NamedTypeSymbol)scope, ref emittedTypeName); } } return namedType; } /// <summary> /// Finds types or namespaces described by a qualified name. /// </summary> /// <param name="qualifiedName">Sequence of simple plain names.</param> /// <returns> /// A set of namespace or type symbols with given qualified name (might comprise of types with multiple generic arities), /// or an empty set if the member can't be found (the qualified name is ambiguous or the symbol doesn't exist). /// </returns> /// <remarks> /// "C.D" matches C.D, C{T}.D, C{S,T}.D{U}, etc. /// </remarks> internal IEnumerable<NamespaceOrTypeSymbol>? GetNamespaceOrTypeByQualifiedName(IEnumerable<string> qualifiedName) { NamespaceOrTypeSymbol namespaceOrType = this; IEnumerable<NamespaceOrTypeSymbol>? symbols = null; foreach (string name in qualifiedName) { if (symbols != null) { // there might be multiple types of different arity, prefer a non-generic type: namespaceOrType = symbols.OfMinimalArity(); if ((object)namespaceOrType == null) { return SpecializedCollections.EmptyEnumerable<NamespaceOrTypeSymbol>(); } } symbols = namespaceOrType.GetMembers(name).OfType<NamespaceOrTypeSymbol>(); } return symbols; } } }
1
dotnet/roslyn
56,218
Eliminate 75GB allocations during binding in a performance trace
Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
sharwell
"2021-09-07T16:51:03Z"
"2021-09-09T22:25:38Z"
e3e8c6e5196d73d1b7582d40a3c48a22c68e6441
ba2203796b7906d6f53b53bc6fa93f1708e11944
Eliminate 75GB allocations during binding in a performance trace. Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
./src/Compilers/CSharp/Portable/Symbols/Source/SourceMemberContainerSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type symbol whose members are declared in source. /// </summary> internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol { // The flags type is used to compact many different bits of information efficiently. private struct Flags { // We current pack everything into one 32-bit int; layout is given below. // // | |vvv|zzzz|f|d|yy|wwwwww| // // w = special type. 6 bits. // y = IsManagedType. 2 bits. // d = FieldDefinitionsNoted. 1 bit // f = FlattenedMembersIsSorted. 1 bit. // z = TypeKind. 4 bits. // v = NullableContext. 3 bits. private int _flags; private const int SpecialTypeOffset = 0; private const int SpecialTypeSize = 6; private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize; private const int ManagedKindSize = 2; private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize; private const int FieldDefinitionsNotedSize = 1; private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize; private const int FlattenedMembersIsSortedSize = 1; private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize; private const int TypeKindSize = 4; private const int NullableContextOffset = TypeKindOffset + TypeKindSize; private const int NullableContextSize = 3; private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1; private const int ManagedKindMask = (1 << ManagedKindSize) - 1; private const int TypeKindMask = (1 << TypeKindSize) - 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset; private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset; public SpecialType SpecialType { get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); } } public ManagedKind ManagedKind { get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); } } public bool FieldDefinitionsNoted { get { return (_flags & FieldDefinitionsNotedBit) != 0; } } // True if "lazyMembersFlattened" is sorted. public bool FlattenedMembersIsSorted { get { return (_flags & FlattenedMembersIsSortedBit) != 0; } } public TypeKind TypeKind { get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif public Flags(SpecialType specialType, TypeKind typeKind) { int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset; int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset; _flags = specialTypeInt | typeKindInt; } public void SetFieldDefinitionsNoted() { ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit); } public void SetFlattenedMembersIsSorted() { ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit)); } private static bool BitsAreUnsetOrSame(int bits, int mask) { return (bits & mask) == 0 || (bits & mask) == mask; } public void SetManagedKind(ManagedKind managedKind) { int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset; Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet)); ThreadSafeFlagOperations.Set(ref _flags, bitsToSet); } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary = PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer); protected SymbolCompletionState state; private Flags _flags; private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics; private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies; private readonly DeclarationModifiers _declModifiers; private readonly NamespaceOrTypeSymbol _containingSymbol; protected readonly MergedTypeDeclaration declaration; // The entry point symbol (resulting from top-level statements) is needed to construct non-type members because // it contributes to their binders, so we have to compute it first. // The value changes from "default" to "real value". The transition from "default" can only happen once. private ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> _lazySimpleProgramEntryPoints; // To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set) // The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once. private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel; private MembersAndInitializers? _lazyMembersAndInitializers; private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary; private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary; private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance); private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers; private ImmutableArray<Symbol> _lazyMembersFlattened; private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations; private int _lazyKnownCircularStruct; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; private ThreeState _lazyContainsExtensionMethods; private ThreeState _lazyAnyMemberHasAttributes; #region Construction internal SourceMemberContainerTypeSymbol( NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData? tupleData = null) : base(tupleData) { // If we're dealing with a simple program, then we must be in the global namespace Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram)); _containingSymbol = containingSymbol; this.declaration = declaration; TypeKind typeKind = declaration.Kind.ToTypeKind(); var modifiers = MakeModifiers(typeKind, diagnostics); foreach (var singleDeclaration in declaration.Declarations) { diagnostics.AddRange(singleDeclaration.Diagnostics); } int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask); if ((access & (access - 1)) != 0) { // more than one access modifier if ((modifiers & DeclarationModifiers.Partial) != 0) diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this); access = access & ~(access - 1); // narrow down to one access modifier modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all modifiers |= (DeclarationModifiers)access; // except the one } _declModifiers = modifiers; var specialType = access == (int)DeclarationModifiers.Public ? MakeSpecialType() : SpecialType.None; _flags = new Flags(specialType, typeKind); var containingType = this.ContainingType; if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected()) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this); } state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately } private SpecialType MakeSpecialType() { // check if this is one of the COR library types if (ContainingSymbol.Kind == SymbolKind.Namespace && ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) { //for a namespace, the emitted name is a dot-separated list of containing namespaces var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName); return SpecialTypes.GetTypeFromMetadataName(emittedName); } else { return SpecialType.None; } } private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics) { Symbol containingSymbol = this.ContainingSymbol; DeclarationModifiers defaultAccess; var allowedModifiers = DeclarationModifiers.AccessibilityMask; if (containingSymbol.Kind == SymbolKind.Namespace) { defaultAccess = DeclarationModifiers.Internal; } else { allowedModifiers |= DeclarationModifiers.New; if (((NamedTypeSymbol)containingSymbol).IsInterface) { defaultAccess = DeclarationModifiers.Public; } else { defaultAccess = DeclarationModifiers.Private; } } switch (typeKind) { case TypeKind.Class: case TypeKind.Submission: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Unsafe; if (!this.IsRecord) { allowedModifiers |= DeclarationModifiers.Static; } break; case TypeKind.Struct: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe; if (!this.IsRecordStruct) { allowedModifiers |= DeclarationModifiers.Ref; } break; case TypeKind.Interface: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; break; case TypeKind.Delegate: allowedModifiers |= DeclarationModifiers.Unsafe; break; } bool modifierErrors; var mods = MakeAndCheckTypeModifiers( defaultAccess, allowedModifiers, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); if (!modifierErrors && (mods & DeclarationModifiers.Abstract) != 0 && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this); } if (!modifierErrors && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) { diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this); } switch (typeKind) { case TypeKind.Interface: mods |= DeclarationModifiers.Abstract; break; case TypeKind.Struct: case TypeKind.Enum: mods |= DeclarationModifiers.Sealed; break; case TypeKind.Delegate: mods |= DeclarationModifiers.Sealed; break; } return mods; } private DeclarationModifiers MakeAndCheckTypeModifiers( DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { modifierErrors = false; var result = DeclarationModifiers.Unset; var partCount = declaration.Declarations.Length; var missingPartial = false; for (var i = 0; i < partCount; i++) { var decl = declaration.Declarations[i]; var mods = decl.Modifiers; if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0) { missingPartial = true; } if (!modifierErrors) { mods = ModifierUtils.CheckModifiers( mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics, modifierTokens: null, modifierErrors: out modifierErrors); // It is an error for the same modifier to appear multiple times. if (!modifierErrors) { var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, this.Locations[0]); modifierErrors = true; } } } if (result == DeclarationModifiers.Unset) { result = mods; } else { result |= mods; } } if ((result & DeclarationModifiers.AccessibilityMask) == 0) { result |= defaultAccess; } if (missingPartial) { if ((result & DeclarationModifiers.Partial) == 0) { // duplicate definitions switch (this.ContainingSymbol.Kind) { case SymbolKind.Namespace: for (var i = 1; i < partCount; i++) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol); modifierErrors = true; } break; case SymbolKind.NamedType: for (var i = 1; i < partCount; i++) { if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial()) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name); modifierErrors = true; } break; } } else { for (var i = 0; i < partCount; i++) { var singleDeclaration = declaration.Declarations[i]; var mods = singleDeclaration.Modifiers; if ((mods & DeclarationModifiers.Partial) == 0) { diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name); modifierErrors = true; } } } } if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword)) { foreach (var syntaxRef in SyntaxReferences) { SyntaxToken? identifier = syntaxRef.GetSyntax() switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => null }; ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None); } } return result; } internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location) { if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) && compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion()) { diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name); } } #endregion #region Completion internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } protected abstract void CheckBase(BindingDiagnosticBag diagnostics); protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics); internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) { while (true) { // NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers. cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartBaseType: case CompletionPart.FinishBaseType: if (state.NotePartComplete(CompletionPart.StartBaseType)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckBase(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishBaseType); diagnostics.Free(); } break; case CompletionPart.StartInterfaces: case CompletionPart.FinishInterfaces: if (state.NotePartComplete(CompletionPart.StartInterfaces)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckInterfaces(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishInterfaces); diagnostics.Free(); } break; case CompletionPart.EnumUnderlyingType: var discarded = this.EnumUnderlyingType; break; case CompletionPart.TypeArguments: { var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments } break; case CompletionPart.TypeParameters: // force type parameters foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.Members: this.GetMembersByName(); break; case CompletionPart.TypeMembers: this.GetTypeMembersUnordered(); break; case CompletionPart.SynthesizedExplicitImplementations: this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked break; case CompletionPart.StartMemberChecks: case CompletionPart.FinishMemberChecks: if (state.NotePartComplete(CompletionPart.StartMemberChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); AfterMembersChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); // We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.MembersCompleted: { ImmutableArray<Symbol> members = this.GetMembersUnordered(); bool allCompleted = true; if (locationOpt == null) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (!allCompleted) { // We did not complete all members so we won't have enough information for // the PointedAtManagedTypeChecks, so just kick out now. var allParts = CompletionPart.NamedTypeSymbolWithLocationAll; state.SpinWaitComplete(allParts, cancellationToken); return; } EnsureFieldDefinitionsNoted(); // We've completed all members, so we're ready for the PointedAtManagedTypeChecks; // proceed to the next iteration. state.NotePartComplete(CompletionPart.MembersCompleted); break; } case CompletionPart.None: return; default: // This assert will trigger if we forgot to handle any of the completion parts Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0); // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } throw ExceptionUtilities.Unreachable; } internal void EnsureFieldDefinitionsNoted() { if (_flags.FieldDefinitionsNoted) { return; } NoteFieldDefinitions(); } private void NoteFieldDefinitions() { // we must note all fields once therefore we need to lock var membersAndInitializers = this.GetMembersAndInitializers(); lock (membersAndInitializers) { if (!_flags.FieldDefinitionsNoted) { var assembly = (SourceAssemblySymbol)ContainingAssembly; Accessibility containerEffectiveAccessibility = EffectiveAccessibility(); foreach (var member in membersAndInitializers.NonTypeMembers) { FieldSymbol field; if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer) { continue; } Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility; if (fieldDeclaredAccessibility == Accessibility.Private) { // mark private fields as tentatively unassigned and unread unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true); } else if (containerEffectiveAccessibility == Accessibility.Private) { // mark effectively private fields as tentatively unassigned unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false); } else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal) { // mark effectively internal fields as tentatively unassigned unless we discover otherwise. // NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly. // See property SourceAssemblySymbol.UnusedFieldWarnings. assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false); } } _flags.SetFieldDefinitionsNoted(); } } } #endregion #region Containers public sealed override NamedTypeSymbol? ContainingType { get { return _containingSymbol as NamedTypeSymbol; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } #endregion #region Flags Encoded Properties public override SpecialType SpecialType { get { return _flags.SpecialType; } } public override TypeKind TypeKind { get { return _flags.TypeKind; } } internal MergedTypeDeclaration MergedDeclaration { get { return this.declaration; } } internal sealed override bool IsInterface { get { // TypeKind is computed eagerly, so this is cheap. return this.TypeKind == TypeKind.Interface; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var managedKind = _flags.ManagedKind; if (managedKind == ManagedKind.Unknown) { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly); managedKind = base.GetManagedKind(ref managedKindUseSiteInfo); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty); _flags.SetManagedKind(managedKind); } if (useSiteInfo.AccumulatesDiagnostics) { ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics; // Ensure we have the latest value from the field useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics); Debug.Assert(!useSiteDiagnostics.IsDefault); useSiteInfo.AddDiagnostics(useSiteDiagnostics); } if (useSiteInfo.AccumulatesDependencies) { ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies; // Ensure we have the latest value from the field useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies); Debug.Assert(!useSiteDependencies.IsDefault); useSiteInfo.AddDependencies(useSiteDependencies); } return managedKind; } public override bool IsStatic => HasFlag(DeclarationModifiers.Static); public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref); public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly); public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed); public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract); internal bool IsPartial => HasFlag(DeclarationModifiers.Partial); internal bool IsNew => HasFlag(DeclarationModifiers.New); [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0; public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_declModifiers); } } /// <summary> /// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields. /// </summary> private Accessibility EffectiveAccessibility() { var result = DeclaredAccessibility; if (result == Accessibility.Private) return Accessibility.Private; for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType) { switch (container.DeclaredAccessibility) { case Accessibility.Private: return Accessibility.Private; case Accessibility.Internal: result = Accessibility.Internal; continue; } } return result; } #endregion #region Syntax public override bool IsScriptClass { get { var kind = this.declaration.Declarations[0].Kind; return kind == DeclarationKind.Script || kind == DeclarationKind.Submission; } } public override bool IsImplicitClass { get { return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass; } } internal override bool IsRecord { get { return this.declaration.Declarations[0].Kind == DeclarationKind.Record; } } internal override bool IsRecordStruct { get { return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct; } } public override bool IsImplicitlyDeclared { get { return IsImplicitClass || IsScriptClass; } } public override int Arity { get { return declaration.Arity; } } public override string Name { get { return declaration.Name; } } internal override bool MangleName { get { return Arity > 0; } } internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public override ImmutableArray<Location> Locations { get { return declaration.NameLocations.Cast<SourceLocation, Location>(); } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return this.declaration.SyntaxReferences; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return SyntaxReferences; } } // This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { var declarations = declaration.Declarations; if (IsImplicitlyDeclared && declarations.IsEmpty) { return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var syntaxRef = declaration.SyntaxReference; if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } #endregion #region Members /// <summary> /// Encapsulates information about the non-type members of a (i.e. this) type. /// 1) For non-initializers, symbols are created and stored in a list. /// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are /// stored with other initialized fields and properties from the same syntax tree with /// the same static-ness. /// </summary> protected sealed class MembersAndInitializers { internal readonly ImmutableArray<Symbol> NonTypeMembers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; internal readonly bool HaveIndexers; internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields; internal readonly bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields) { Debug.Assert(!nonTypeMembers.IsDefault); Debug.Assert(!staticInitializers.IsDefault); Debug.Assert(staticInitializers.All(g => !g.IsDefault)); Debug.Assert(!instanceInitializers.IsDefault); Debug.Assert(instanceInitializers.All(g => !g.IsDefault)); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer())); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers { get { return GetMembersAndInitializers().StaticInitializers; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers { get { return GetMembersAndInitializers().InstanceInitializers; } } internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic) { if (IsScriptClass && !isStatic) { int aggregateLength = 0; foreach (var declaration in this.declaration.Declarations) { var syntaxRef = declaration.SyntaxReference; if (tree == syntaxRef.SyntaxTree) { return aggregateLength + position; } aggregateLength += syntaxRef.Span.Length; } throw ExceptionUtilities.Unreachable; } int syntaxOffset; if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset)) { return syntaxOffset; } if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start) { // With dynamic analysis instrumentation, the introducing declaration of a type can provide // the syntax associated with both the analysis payload local of a synthesized constructor // and with the constructor itself. If the synthesized constructor includes an initializer with a lambda, // that lambda needs a closure that captures the analysis payload of the constructor, // and the offset of the syntax for the local within the constructor is by definition zero. return 0; } // an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer throw ExceptionUtilities.Unreachable; } /// <summary> /// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one). /// </summary> internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset) { Debug.Assert(ctorInitializerLength >= 0); var membersAndInitializers = GetMembersAndInitializers(); var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers; if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength)) { syntaxOffset = 0; return false; } // |<-----------distanceFromCtorBody----------->| // [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body] // |<--preceding init len-->| ^ // position int initializersLength = getInitializersLength(allInitializers); int distanceFromInitializerStart = position - initializer.Syntax.Span.Start; int distanceFromCtorBody = initializersLength + ctorInitializerLength - (precedingLength + distanceFromInitializerStart); Debug.Assert(distanceFromCtorBody > 0); // syntax offset 0 is at the start of the ctor body: syntaxOffset = -distanceFromCtorBody; return true; static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree, out FieldOrPropertyInitializer found, out int precedingLength) { precedingLength = 0; foreach (var group in initializers) { if (!group.IsEmpty && group[0].Syntax.SyntaxTree == tree && position < group.Last().Syntax.Span.End) { // Found group of interest var initializerIndex = IndexOfInitializerContainingPosition(group, position); if (initializerIndex < 0) { break; } precedingLength += getPrecedingInitializersLength(group, initializerIndex); found = group[initializerIndex]; return true; } precedingLength += getGroupLength(group); } found = default; return false; } static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers) { int length = 0; foreach (var initializer in initializers) { length += getInitializerLength(initializer); } return length; } static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index) { int length = 0; for (var i = 0; i < index; i++) { length += getInitializerLength(initializers[i]); } return length; } static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { int length = 0; foreach (var group in initializers) { length += getGroupLength(group); } return length; } static int getInitializerLength(FieldOrPropertyInitializer initializer) { // A constant field of type decimal needs a field initializer, so // check if it is a metadata constant, not just a constant to exclude // decimals. Other constants do not need field initializers. if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant) { // ignore leading and trailing trivia of the node: return initializer.Syntax.Span.Length; } return 0; } } private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position) { // Search for the start of the span (the spans are non-overlapping and sorted) int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos)); // Binary search returns non-negative result if the position is exactly the start of some span. if (index >= 0) { return index; } // Otherwise, ~index is the closest span whose start is greater than the position. // => Check if the preceding initializer span contains the position. int precedingInitializerIndex = ~index - 1; if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position)) { return precedingInitializerIndex; } return -1; } public override IEnumerable<string> MemberNames { get { return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembersDictionary().Flatten(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; if (GetTypeMembersDictionary().TryGetValue(name, out members)) { return members; } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary() { if (_lazyTypeMembers == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.TypeMembers); } diagnostics.Free(); } return _lazyTypeMembers; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>(); try { foreach (var childDeclaration in declaration.Children) { var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics); this.CheckMemberNameDistinctFromType(t, diagnostics); var key = (t.Name, t.Arity); SourceNamedTypeSymbol? other; if (conflictDict.TryGetValue(key, out other)) { if (Locations.Length == 1 || IsPartial) { if (t.IsPartial && other.IsPartial) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name); } } } else { conflictDict.Add(key, t); } symbols.Add(t); } if (IsInterface) { foreach (var t in symbols) { Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]); } } Debug.Assert(s_emptyTypeMembers.Count == 0); return symbols.Count > 0 ? symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) : s_emptyTypeMembers; } finally { symbols.Free(); } } private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics) { switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: if (member.Name == this.Name) { diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name); } break; case TypeKind.Interface: if (member.IsStatic) { goto case TypeKind.Class; } break; } } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyMembersFlattened; if (result.IsDefault) { result = GetMembersByName().Flatten(null); // do not sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result); result = _lazyMembersFlattened; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if (_flags.FlattenedMembersIsSorted) { return _lazyMembersFlattened; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length > 1) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers); } _flags.SetFlattenedMembersIsSorted(); return allMembers; } } public sealed override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<Symbol> members; if (GetMembersByName().TryGetValue(name, out members)) { return members; } return ImmutableArray<Symbol>.Empty; } /// <remarks> /// For source symbols, there can only be a valid clone method if this is a record, which is a /// simple syntax check. This will need to change when we generalize cloning, but it's a good /// heuristic for now. /// </remarks> internal override bool HasPossibleWellKnownCloneMethod() => IsRecord; internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct) { return GetMembers(name); } return ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { // For consistency with Dev10, emit value__ field first. var valueField = ((SourceNamedTypeSymbol)this).EnumValueField; RoslynDebug.Assert((object)valueField != null); yield return valueField; } foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: if (m is TupleErrorFieldSymbol) { break; } yield return (FieldSymbol)m; break; case SymbolKind.Event: FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField; if ((object?)associatedField != null) { yield return associatedField; } break; } } } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return GetEarlyAttributeDecodingMembersDictionary().Flatten(); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { ImmutableArray<Symbol> result; return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty; } private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary() { if (_lazyEarlyAttributeDecodingMembersDictionary == null) { if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result) { return result; } var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached // NOTE: members were added in a single pass over the syntax, so they're already // in lexical order. Dictionary<string, ImmutableArray<Symbol>> membersByName; if (!membersAndInitializers.HaveIndexers) { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name); } else { // We can't include indexer symbol yet, because we don't know // what name it will have after attribute binding (because of // IndexerNameAttribute). membersByName = membersAndInitializers.NonTypeMembers. WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)). ToDictionary(s => s.Name); } AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null); } return _lazyEarlyAttributeDecodingMembersDictionary; } // NOTE: this method should do as little work as possible // we often need to get members just to do a lookup. // All additional checks and diagnostics may be not // needed yet or at all. protected MembersAndInitializers GetMembersAndInitializers() { var membersAndInitializers = _lazyMembersAndInitializers; if (membersAndInitializers != null) { return membersAndInitializers; } var diagnostics = BindingDiagnosticBag.GetInstance(); membersAndInitializers = BuildMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null); if (alreadyKnown != null) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); _lazyDeclaredMembersAndInitializers = null; return membersAndInitializers!; } /// <summary> /// The purpose of this function is to assert that the <paramref name="member"/> symbol /// is actually among the symbols cached by this type symbol in a way that ensures /// that any consumer of standard APIs to get to type's members is going to get the same /// symbol (same instance) for the member rather than an equivalent, but different instance. /// </summary> [Conditional("DEBUG")] internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false) { if (member is FieldSymbol && forDiagnostics && this.IsTupleType) { // There is a problem with binding types of fields in tuple types. // Skipping verification for them temporarily. return; } if (member is NamedTypeSymbol type) { RoslynDebug.AssertOrFailFast(forDiagnostics); RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true); return; } else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol) { RoslynDebug.AssertOrFailFast(forDiagnostics); return; } else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e) { RoslynDebug.AssertOrFailFast(forDiagnostics); // Backing fields for field-like events are not added to the members list. member = e; } var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } if (membersAndInitializers is null) { if (member is SynthesizedSimpleProgramEntryPointSymbol) { RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member)); return; } var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers); RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel); if (declared is object) { if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member) { return; } } else { // It looks like there was a race and we need to check _lazyMembersAndInitializers again membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); RoslynDebug.AssertOrFailFast(membersAndInitializers is object); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } } } RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure."); static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member) { return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true; } } protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName() { if (this.state.HasComplete(CompletionPart.Members)) { return _lazyMembersDictionary!; } return GetMembersByNameSlow(); } private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow() { if (_lazyMembersDictionary == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var membersDictionary = MakeAllMembers(diagnostics); if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.Members); } diagnostics.Free(); } state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken)); return _lazyMembersDictionary; } internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents() { var membersAndInitializers = this.GetMembersAndInitializers(); return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent); } protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) { if (IsInterface) { CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics); } CheckMemberNamesDistinctFromType(diagnostics); CheckMemberNameConflicts(diagnostics); CheckRecordMemberNames(diagnostics); CheckSpecialMemberErrors(diagnostics); CheckTypeParameterNameConflicts(diagnostics); CheckAccessorNameConflicts(diagnostics); bool unused = KnownCircularStruct; CheckSequentialOnPartialType(diagnostics); CheckForProtectedInStaticClass(diagnostics); CheckForUnmatchedOperators(diagnostics); var location = Locations[0]; var compilation = DeclaringCompilation; if (this.IsRefLikeType) { compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true); } if (this.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } var baseType = BaseTypeNoUseSiteDiagnostics; var interfaces = GetInterfacesToEmit(); // https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations. if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger())) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute())) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } } if (interfaces.Any(t => needsTupleElementNamesAttribute(t))) { // Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding) // so the checking of all interfaces here involves some redundancy. Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics); } bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate) { return ((object)baseType != null && predicate(baseType)) || interfaces.Any(predicate); } static bool needsTupleElementNamesAttribute(TypeSymbol type) { if (type is null) { return false; } var resultType = type.VisitType( predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(), arg: (object?)null); return resultType is object; } } private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics) { foreach (var member in GetMembersAndInitializers().NonTypeMembers) { CheckMemberNameDistinctFromType(member, diagnostics); } } private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics) { if (declaration.Kind != DeclarationKind.Record && declaration.Kind != DeclarationKind.RecordStruct) { return; } foreach (var member in GetMembers("Clone")) { diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]); } } private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName(); // Collisions involving indexers are handled specially. CheckIndexerNameConflicts(diagnostics, membersByName); // key and value will be the same object in these dictionaries. var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer); // SPEC: The signature of an operator must differ from the signatures of all other // SPEC: operators declared in the same class. // DELIBERATE SPEC VIOLATION: // The specification does not state that a user-defined conversion reserves the names // op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt // to define a field or a conflicting method with the metadata name of a user-defined // conversion is an error. We preserve this reasonable behavior. // // Similarly, we treat "public static C operator +(C, C)" as colliding with // "public static C op_Addition(C, C)". Fortunately, this behavior simply // falls out of treating user-defined operators as ordinary methods; we do // not need any special handling in this method. // // However, we must have special handling for conversions because conversions // use a completely different rule for detecting collisions between two // conversions: conversion signatures consist only of the source and target // types of the conversions, and not the kind of the conversion (implicit or explicit), // the name of the method, and so on. // // Therefore we must detect the following kinds of member name conflicts: // // 1. a method, conversion or field has the same name as a (different) field (* see note below) // 2. a method has the same method signature as another method or conversion // 3. a conversion has the same conversion signature as another conversion. // // However, we must *not* detect "a conversion has the same *method* signature // as another conversion" because conversions are allowed to overload on // return type but methods are not. // // (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for // "non-method, non-conversion, non-type member", rather than spelling out // "field, property or event...") foreach (var pair in membersByName) { var name = pair.Key; Symbol? lastSym = GetTypeMembers(name).FirstOrDefault(); methodsBySignature.Clear(); // Conversion collisions do not consider the name of the conversion, // so do not clear that dictionary. foreach (var symbol in pair.Value) { if (symbol.Kind == SymbolKind.NamedType || symbol.IsAccessor() || symbol.IsIndexer()) { continue; } // We detect the first category of conflict by running down the list of members // of the same name, and producing an error when we discover any of the following // "bad transitions". // // * a method or conversion that comes after any field (not necessarily directly) // * a field directly following a field // * a field directly following a method or conversion // // Furthermore: we do not wish to detect collisions between nested types in // this code; that is tested elsewhere. However, we do wish to detect a collision // between a nested type and a field, method or conversion. Therefore we // initialize our "bad transition" detector with a type of the given name, // if there is one. That way we also detect the transitions of "method following // type", and so on. // // The "lastSym" local below is used to detect these transitions. Its value is // one of the following: // // * a nested type of the given name, or // * the first method of the given name, or // * the most recently processed field of the given name. // // If either the current symbol or the "last symbol" are not methods then // there must be a collision: // // * if the current symbol is not a method and the last symbol is, then // there is a field directly following a method of the same name // * if the current symbol is a method and the last symbol is not, then // there is a method directly or indirectly following a field of the same name, // or a method of the same name as a nested type. // * if neither are methods then either we have a field directly // following a field of the same name, or a field and a nested type of the same name. // if (lastSym is object) { if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method) { if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name); } } if (lastSym.Kind == SymbolKind.Method) { lastSym = symbol; } } } else { lastSym = symbol; } // That takes care of the first category of conflict; we detect the // second and third categories as follows: var conversion = symbol as SourceUserDefinedConversionSymbol; var method = symbol as SourceMemberMethodSymbol; if (!(conversion is null)) { // Does this conversion collide *as a conversion* with any previously-seen // conversion? if (!conversionsAsConversions.Add(conversion)) { // CS0557: Duplicate user-defined conversion in type 'C' diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this); } else { // The other set might already contain a conversion which would collide // *as a method* with the current conversion. if (!conversionsAsMethods.ContainsKey(conversion)) { conversionsAsMethods.Add(conversion, conversion); } } // Does this conversion collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(conversion, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, conversion, previousMethod); } // Do not add the conversion to the set of previously-seen methods; that set // is only non-conversion methods. } else if (!(method is null)) { // Does this method collide *as a method* with any previously-seen // conversion? if (conversionsAsMethods.TryGetValue(method, out var previousConversion)) { ReportMethodSignatureCollision(diagnostics, method, previousConversion); } // Do not add the method to the set of previously-seen conversions. // Does this method collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(method, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, method, previousMethod); } else { // We haven't seen this method before. Make a note of it in case // we see a colliding method later. methodsBySignature.Add(method, method); } } } } } // Report a name conflict; the error is reported on the location of method1. // UNDONE: Consider adding a secondary location pointing to the second method. private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2) { switch (method1, method2) { case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }): case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }): // these could be 2 parts of the same partial method. // Partial methods are allowed to collide by signature. return; case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }): return; } // If method1 is a constructor only because its return type is missing, then // we've already produced a diagnostic for the missing return type and we suppress the // diagnostic about duplicate signature. if (method1.MethodKind == MethodKind.Constructor && ((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name) { return; } Debug.Assert(method1.ParameterCount == method2.ParameterCount); for (int i = 0; i < method1.ParameterCount; i++) { var refKind1 = method1.Parameters[i].RefKind; var refKind2 = method2.Parameters[i].RefKind; if (refKind1 != refKind2) { // '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}' var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD; diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString()); return; } } // Special case: if there are two destructors, use the destructor syntax instead of "Finalize" var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ? "~" + this.Name : (method1.IsConstructor() ? this.Name : method1.Name); // Type '{1}' already defines a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this); } private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName) { PooledHashSet<string>? typeParameterNames = null; if (this.Arity > 0) { typeParameterNames = PooledHashSet<string>.GetInstance(); foreach (TypeParameterSymbol typeParameter in this.TypeParameters) { typeParameterNames.Add(typeParameter.Name); } } var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer); // Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because // they may be explicit interface implementations. foreach (var members in membersByName.Values) { string? lastIndexerName = null; indexersBySignature.Clear(); foreach (var symbol in members) { if (symbol.IsIndexer()) { PropertySymbol indexer = (PropertySymbol)symbol; CheckIndexerSignatureCollisions( indexer, diagnostics, membersByName, indexersBySignature, ref lastIndexerName); // Also check for collisions with type parameters, which aren't in the member map. // NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts. if (typeParameterNames != null) { string indexerName = indexer.MetadataName; if (typeParameterNames.Contains(indexerName)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); continue; } } } } } typeParameterNames?.Free(); } private void CheckIndexerSignatureCollisions( PropertySymbol indexer, BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<PropertySymbol, PropertySymbol> indexersBySignature, ref string? lastIndexerName) { if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked { string indexerName = indexer.MetadataName; if (lastIndexerName != null && lastIndexerName != indexerName) { // NOTE: dev10 checks indexer names by comparing each to the previous. // For example, if indexers are declared with names A, B, A, B, then there // will be three errors - one for each time the name is different from the // previous one. If, on the other hand, the names are A, A, B, B, then // there will only be one error because only one indexer has a different // name from the previous one. diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]); } lastIndexerName = indexerName; if (Locations.Length == 1 || IsPartial) { if (membersByName.ContainsKey(indexerName)) { // The name of the indexer is reserved - it can only be used by other indexers. Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer)); diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); } } } if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature)) { // Type '{1}' already defines a member called '{0}' with the same parameter types // NOTE: Dev10 prints "this" as the name of the indexer. diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this); } else { indexersBySignature[indexer] = indexer; } } private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics) { var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary); foreach (var member in this.GetMembersUnordered()) { member.AfterAddingTypeMembersChecks(conversions, diagnostics); } } private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics) { if (this.TypeKind == TypeKind.Delegate) { // Delegates do not have conflicts between their type parameter // names and their methods; it is legal (though odd) to say // delegate void D<Invoke>(Invoke x); return; } if (Locations.Length == 1 || IsPartial) { foreach (var tp in TypeParameters) { foreach (var dup in GetMembers(tp.Name)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name); } } } } private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics) { // Report errors where property and event accessors // conflict with other members of the same name. foreach (Symbol symbol in this.GetMembersUnordered()) { if (symbol.IsExplicitInterfaceImplementation()) { // If there's a name conflict it will show up as a more specific // interface implementation error. continue; } switch (symbol.Kind) { case SymbolKind.Property: { var propertySymbol = (PropertySymbol)symbol; this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics); this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics); break; } case SymbolKind.Event: { var eventSymbol = (EventSymbol)symbol; this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics); this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics); break; } } } } internal override bool KnownCircularStruct { get { if (_lazyKnownCircularStruct == (int)ThreeState.Unknown) { if (TypeKind != TypeKind.Struct) { Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); var value = (int)CheckStructCircularity(diagnostics).ToThreeState(); if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown) { AddDeclarationDiagnostics(diagnostics); } Debug.Assert(value == _lazyKnownCircularStruct); diagnostics.Free(); } } return _lazyKnownCircularStruct == (int)ThreeState.True; } } private bool CheckStructCircularity(BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); CheckFiniteFlatteningGraph(diagnostics); return HasStructCircularity(diagnostics); } private bool HasStructCircularity(BindingDiagnosticBag diagnostics) { foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member.Kind != SymbolKind.Field) { // NOTE: don't have to check field-like events, because they can't have struct types. continue; } var field = (FieldSymbol)member; if (field.IsStatic) { continue; } var type = field.NonPointerType(); if (((object)type != null) && (type.TypeKind == TypeKind.Struct) && BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) && !type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type { // If this is a backing field, report the error on the associated property. var symbol = field.AssociatedSymbol ?? field; if (symbol.Kind == SymbolKind.Parameter) { // We should stick to members for this error. symbol = field; } // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type); return true; } } } return false; } private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) { if (!IsStatic) { return; } // no protected members allowed foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member is TypeSymbol) { // Duplicate Dev10's failure to diagnose this error. continue; } if (member.DeclaredAccessibility.HasProtected()) { if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor) { diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member); } } } } } private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) { // SPEC: The true and false unary operators require pairwise declaration. // SPEC: A compile-time error occurs if a class or struct declares one // SPEC: of these operators without also declaring the other. // // SPEC DEFICIENCY: The line of the specification quoted above should say // the same thing as the lines below: that the formal parameters of the // paired true/false operators must match exactly. You can't do // op true(S) and op false(S?) for example. // SPEC: Certain binary operators require pairwise declaration. For every // SPEC: declaration of either operator of a pair, there must be a matching // SPEC: declaration of the other operator of the pair. Two operator // SPEC: declarations match when they have the same return type and the same // SPEC: type for each parameter. The following operators require pairwise // SPEC: declaration: == and !=, > and <, >= and <=. CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); // We also produce a warning if == / != is overridden without also overriding // Equals and GetHashCode, or if Equals is overridden without GetHashCode. CheckForEqualityAndGetHashCode(diagnostics); } private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2) { var ops1 = this.GetOperators(operatorName1); var ops2 = this.GetOperators(operatorName2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2); CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1); } private static void CheckForUnmatchedOperator( BindingDiagnosticBag diagnostics, ImmutableArray<MethodSymbol> ops1, ImmutableArray<MethodSymbol> ops2, string operatorName2) { foreach (var op1 in ops1) { bool foundMatch = false; foreach (var op2 in ops2) { foundMatch = DoOperatorsPair(op1, op2); if (foundMatch) { break; } } if (!foundMatch) { // CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2))); } } } private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) { if (op1.ParameterCount != op2.ParameterCount) { return false; } for (int p = 0; p < op1.ParameterCount; ++p) { if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions)) { return false; } } if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions)) { return false; } return true; } private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) { if (this.IsInterfaceType()) { // Interfaces are allowed to define Equals without GetHashCode if they want. return; } if (IsRecord || IsRecordStruct) { // For records the warnings reported below are simply going to echo record specific errors, // producing more noise. return; } bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() || this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any(); bool overridesEquals = this.TypeOverridesObjectMethod("Equals"); if (hasOp || overridesEquals) { bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode"); if (overridesEquals && !overridesGHC) { // CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this); } if (hasOp && !overridesEquals) { // CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o) diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this); } if (hasOp && !overridesGHC) { // CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this); } } } private bool TypeOverridesObjectMethod(string name) { foreach (var method in this.GetMembers(name).OfType<MethodSymbol>()) { if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object) { return true; } } return false; } private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics) { Debug.Assert(ReferenceEquals(this, this.OriginalDefinition)); if (AllTypeArgumentCount() == 0) return; var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance); instanceMap.Add(this, this); foreach (var m in this.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(this, type, instanceMap)) { // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type); //this.KnownCircularStruct = true; return; } } } private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap) { if (!t.ContainsTypeParameter()) return false; var tOriginal = t.OriginalDefinition; if (instanceMap.TryGetValue(tOriginal, out var oldInstance)) { // short circuit when we find a cycle, but only return true when the cycle contains the top struct return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top); } else { instanceMap.Add(tOriginal, t); try { foreach (var m in t.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(top, type, instanceMap)) return true; } return false; } finally { instanceMap.Remove(tOriginal); } } } private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics) { if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential) { return; } SyntaxReference? whereFoundField = null; if (this.SyntaxReferences.Length <= 1) { return; } foreach (var syntaxRef in this.SyntaxReferences) { var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax; if (syntax == null) { continue; } foreach (var m in syntax.Members) { if (HasInstanceData(m)) { if (whereFoundField != null && whereFoundField != syntaxRef) { diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this); return; } whereFoundField = syntaxRef; } } } } private static bool HasInstanceData(MemberDeclarationSyntax m) { switch (m.Kind()) { case SyntaxKind.FieldDeclaration: var fieldDecl = (FieldDeclarationSyntax)m; return !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword); case SyntaxKind.PropertyDeclaration: // auto-property var propertyDecl = (PropertyDeclarationSyntax)m; return !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) && propertyDecl.AccessorList != null && All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null); case SyntaxKind.EventFieldDeclaration: // field-like event declaration var eventFieldDecl = (EventFieldDeclarationSyntax)m; return !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword); default: return false; } } private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode { foreach (var t in list) { if (predicate(t)) return true; }; return false; } private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier) { foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; }; return false; } private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName; var membersAndInitializers = GetMembersAndInitializers(); // Most types don't have indexers. If this is one of those types, // just reuse the dictionary we build for early attribute decoding. // For tuples, we also need to take the slow path. if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object) { membersByName = _lazyEarlyAttributeDecodingMembersDictionary; } else { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); // Merge types into the member dictionary AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); } MergePartialMembers(ref membersByName, diagnostics); return membersByName; } private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName) { foreach (var pair in typesByName) { string name = pair.Key; ImmutableArray<NamedTypeSymbol> types = pair.Value; ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types); ImmutableArray<Symbol> membersForName; if (membersByName.TryGetValue(name, out membersForName)) { membersByName[name] = membersForName.Concat(typesAsSymbols); } else { membersByName.Add(name, typesAsSymbols); } } } private sealed class DeclaredMembersAndInitializersBuilder { public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public bool HaveIndexers; public RecordDeclarationSyntax? RecordDeclarationWithParameters; public SynthesizedRecordConstructor? RecordPrimaryConstructor; public bool IsNullableEnabledForInstanceConstructorsAndFields; public bool IsNullableEnabledForStaticConstructorsAndFields; public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation) { return new DeclaredMembersAndInitializers( NonTypeMembers.ToImmutableAndFree(), MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers), MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers), HaveIndexers, RecordDeclarationWithParameters, RecordPrimaryConstructor, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields, compilation); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || value; } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } public void Free() { NonTypeMembers.Free(); foreach (var group in StaticInitializers) { group.Free(); } StaticInitializers.Free(); foreach (var group in InstanceInitializers) { group.Free(); } InstanceInitializers.Free(); } internal void AddOrWrapTupleMembers(SourceMemberContainerTypeSymbol type) { this.NonTypeMembers = type.AddOrWrapTupleMembers(this.NonTypeMembers.ToImmutableAndFree()); } } protected sealed class DeclaredMembersAndInitializers { public readonly ImmutableArray<Symbol> NonTypeMembers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; public readonly bool HaveIndexers; public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters; public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor; public readonly bool IsNullableEnabledForInstanceConstructorsAndFields; public readonly bool IsNullableEnabledForStaticConstructorsAndFields; public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers(); private DeclaredMembersAndInitializers() { } public DeclaredMembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, RecordDeclarationSyntax? recordDeclarationWithParameters, SynthesizedRecordConstructor? recordPrimaryConstructor, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields, CSharpCompilation compilation) { Debug.Assert(!nonTypeMembers.IsDefault); AssertInitializers(staticInitializers, compilation); AssertInitializers(instanceInitializers, compilation); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.RecordDeclarationWithParameters = recordDeclarationWithParameters; this.RecordPrimaryConstructor = recordPrimaryConstructor; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } [Conditional("DEBUG")] public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation) { Debug.Assert(!initializers.IsDefault); if (initializers.IsEmpty) { return; } foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers) { Debug.Assert(!group.IsDefaultOrEmpty); } for (int i = 0; i < initializers.Length; i++) { if (i > 0) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } if (i + 1 < initializers.Length) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0); } if (initializers[i].Length != 1) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } } } } private sealed class MembersAndInitializersBuilder { public ArrayBuilder<Symbol>? NonTypeMembers; private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers; private bool IsNullableEnabledForInstanceConstructorsAndFields; private bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers) { Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel); this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; } public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers) { var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers; var instanceInitializers = InstanceInitializersForPositionalMembers is null ? declaredMembers.InstanceInitializers : mergeInitializers(); return new MembersAndInitializers( nonTypeMembers, declaredMembers.StaticInitializers, instanceInitializers, declaredMembers.HaveIndexers, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields); ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers() { Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0); Debug.Assert(declaredMembers.RecordPrimaryConstructor is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start)); var groupCount = declaredMembers.InstanceInitializers.Length; if (groupCount == 0) { return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); } var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation; var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation); int insertAt; for (insertAt = 0; insertAt < groupCount; insertAt++) { if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0) { break; } } ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder; if (insertAt != groupCount && declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start)) { // Need to merge into the previous group var declaredInitializers = declaredMembers.InstanceInitializers[insertAt]; var insertedInitializers = InstanceInitializersForPositionalMembers; #if DEBUG // initializers should be added in syntax order: Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree); Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start); #endif insertedInitializers.AddRange(declaredInitializers); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(insertedInitializers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1)); Debug.Assert(groupsBuilder.Count == groupCount); } else { Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start))); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt); Debug.Assert(groupsBuilder.Count == groupCount + 1); } var result = groupsBuilder.ToImmutableAndFree(); DeclaredMembersAndInitializers.AssertInitializers(result, compilation); return result; } } public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer) { if (InstanceInitializersForPositionalMembers is null) { InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } InstanceInitializersForPositionalMembers.Add(initializer); } public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers) { return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers; } public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers) { if (NonTypeMembers is null) { NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1); NonTypeMembers.AddRange(declaredMembers.NonTypeMembers); } NonTypeMembers.Add(member); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers) { if (initializers.Count == 0) { initializers.Free(); return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty; } var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count); foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers) { builder.Add(group.ToImmutableAndFree()); } initializers.Free(); return builder.ToImmutableAndFree(); } public void Free() { NonTypeMembers?.Free(); InstanceInitializersForPositionalMembers?.Free(); } } private MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics) { var declaredMembersAndInitializers = getDeclaredMembersAndInitializers(); if (declaredMembersAndInitializers is null) { // Another thread completed the work before this one return null; } var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers); AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics); if (Volatile.Read(ref _lazyMembersAndInitializers) != null) { // Another thread completed the work before this one membersAndInitializersBuilder.Free(); return null; } return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers); DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers() { var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers; if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) { return declaredMembersAndInitializers; } if (Volatile.Read(ref _lazyMembersAndInitializers) is not null) { // We're previously computed declared members and already cleared them out // No need to compute them again return null; } var diagnostics = BindingDiagnosticBag.GetInstance(); declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel); if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); return declaredMembersAndInitializers!; } // Builds explicitly declared members (as opposed to synthesized members). // This should not attempt to bind any method parameters as that would cause // the members being built to be captured in the binder cache before the final // list of members is determined. DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics) { var builder = new DeclaredMembersAndInitializersBuilder(); AddDeclaredNontypeMembers(builder, diagnostics); switch (TypeKind) { case TypeKind.Struct: CheckForStructBadInitializers(builder, diagnostics); CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics); break; case TypeKind.Enum: CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics); break; case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: // No additional checking required. break; default: break; } if (IsTupleType) { builder.AddOrWrapTupleMembers(this); } if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel) { // _lazyDeclaredMembersAndInitializers is already computed. no point to continue. builder.Free(); return null; } return builder.ToReadOnlyAndFree(DeclaringCompilation); } } internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints() { if (_lazySimpleProgramEntryPoints.IsDefault) { var diagnostics = BindingDiagnosticBag.GetInstance(); var simpleProgramEntryPoints = buildSimpleProgramEntryPoint(diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazySimpleProgramEntryPoints, simpleProgramEntryPoints)) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } Debug.Assert(!_lazySimpleProgramEntryPoints.IsDefault); return _lazySimpleProgramEntryPoints; ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics) { if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true } || this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null; foreach (var singleDecl in declaration.Declarations) { if (singleDecl.IsSimpleProgram) { if (builder is null) { builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance(); } else { Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation); } builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics)); } } if (builder is null) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } return builder.ToImmutableAndFree(); } } private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (TypeKind is TypeKind.Class) { AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers); } switch (TypeKind) { case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics); AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics); break; default: break; } } private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { foreach (var decl in this.declaration.Declarations) { if (!decl.HasAnyNontypeMembers) { continue; } if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } var syntax = decl.SyntaxReference.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.EnumDeclaration: AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.DelegateDeclaration: SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit. AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics); break; case SyntaxKind.CompilationUnit: AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)syntax; AddNonTypeMembers(builder, typeDecl.Members, diagnostics); break; case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var recordDecl = (RecordDeclarationSyntax)syntax; var parameterList = recordDecl.ParameterList; noteRecordParameters(recordDecl, parameterList, builder, diagnostics); AddNonTypeMembers(builder, recordDecl.Members, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { if (parameterList is null) { return; } if (builder.RecordDeclarationWithParameters is null) { builder.RecordDeclarationWithParameters = syntax; var ctor = new SynthesizedRecordConstructor(this, syntax); builder.RecordPrimaryConstructor = ctor; var compilation = DeclaringCompilation; builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList); if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } }) { builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList); } } else { diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location); } } } internal Binder GetBinder(CSharpSyntaxNode syntaxNode) { return this.DeclaringCompilation.GetBinder(syntaxNode); } private void MergePartialMembers( ref Dictionary<string, ImmutableArray<Symbol>> membersByName, BindingDiagnosticBag diagnostics) { var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count); memberNames.AddRange(membersByName.Keys); //key and value will be the same object var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer); foreach (var name in memberNames) { methodsBySignature.Clear(); foreach (var symbol in membersByName[name]) { var method = symbol as SourceMemberMethodSymbol; if (method is null || !method.IsPartial) { continue; // only partial methods need to be merged } if (methodsBySignature.TryGetValue(method, out var prev)) { var prevPart = (SourceOrdinaryMethodSymbol)prev; var methodPart = (SourceOrdinaryMethodSymbol)method; if (methodPart.IsPartialImplementation && (prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart))) { // A partial method may not have multiple implementing declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]); } else if (methodPart.IsPartialDefinition && (prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart))) { // A partial method may not have multiple defining declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]); } else { if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary) { // Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel. membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName); } membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart); } } else { methodsBySignature.Add(method, method); } } foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values) { // partial implementations not paired with a definition if (method.IsPartialImplementation && method.OtherPartOfPartial is null) { diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method); } else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true }) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method); } } } memberNames.Free(); } /// <summary> /// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name), /// and returning the combined symbol. /// </summary> /// <param name="symbols">The symbols array containing both the latent and implementing declaration</param> /// <param name="part1">One of the two declarations</param> /// <param name="part2">The other declaration</param> /// <returns>An updated symbols array containing only one method symbol representing the two parts</returns> private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2) { SourceOrdinaryMethodSymbol definition; SourceOrdinaryMethodSymbol implementation; if (part1.IsPartialDefinition) { definition = part1; implementation = part2; } else { definition = part2; implementation = part1; } SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation); // a partial method is represented in the member list by its definition part: return Remove(symbols, implementation); } private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol) { var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var s in symbols) { if (!ReferenceEquals(s, symbol)) { builder.Add(s); } } return builder.ToImmutableAndFree(); } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the property accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithPropertyAccessor( PropertySymbol propertySymbol, bool getNotSet, BindingDiagnosticBag diagnostics) { Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod; string accessorName; if ((object)accessor != null) { accessorName = accessor.Name; } else { string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name; accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName, getNotSet, propertySymbol.IsCompilationOutputWinMdObj()); } foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this); return; } } } } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the event accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithEventAccessor( EventSymbol eventSymbol, bool isAdder, BindingDiagnosticBag diagnostics) { Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder); foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this); return; } } } } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the property. /// </summary> private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet) { var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the event. /// </summary> private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder) { var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return true if the method parameters match the parameters of the /// property accessor, including the value parameter for the setter. /// </summary> private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams) { var propertyParams = propertySymbol.Parameters; var numParams = propertyParams.Length + (getNotSet ? 0 : 1); if (numParams != methodParams.Length) { return false; } for (int i = 0; i < numParams; i++) { var methodParam = methodParams[i]; if (methodParam.RefKind != RefKind.None) { return false; } var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type; if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions)) { return false; } } return true; } /// <summary> /// Return true if the method parameters match the parameters of the /// event accessor, including the value parameter. /// </summary> private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams) { return methodParams.Length == 1 && methodParams[0].RefKind == RefKind.None && eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions); } private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { // The previous enum constant used to calculate subsequent // implicit enum constants. (This is the most recent explicit // enum constant or the first implicit constant if no explicit values.) SourceEnumConstantSymbol? otherSymbol = null; // Offset from "otherSymbol". int otherSymbolOffset = 0; foreach (var member in syntax.Members) { SourceEnumConstantSymbol symbol; var valueOpt = member.EqualsValue; if (valueOpt != null) { symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics); } else { symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics); } result.NonTypeMembers.Add(symbol); if (valueOpt != null || otherSymbol is null) { otherSymbol = symbol; otherSymbolOffset = 1; } else { otherSymbolOffset++; } } } private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node) { if (initializers == null) { initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } else if (initializers.Count != 0) { // initializers should be added in syntax order: Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree); Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start); } initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node)); } private static void AddInitializers( ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers, ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt) { if (siblingsOpt != null) { allInitializers.Add(siblingsOpt); } } private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics) { foreach (var member in nonTypeMembers) { CheckInterfaceMember(member, diagnostics); } } private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics) { switch (member.Kind) { case SymbolKind.Field: break; case SymbolKind.Method: var meth = (MethodSymbol)member; switch (meth.MethodKind) { case MethodKind.Constructor: diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]); break; case MethodKind.Conversion: if (!meth.IsAbstract) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.UserDefinedOperator: if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName)) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.Destructor: diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]); break; case MethodKind.ExplicitInterfaceImplementation: //CS0541 is handled in SourcePropertySymbol case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.StaticConstructor: break; default: throw ExceptionUtilities.UnexpectedValue(meth.MethodKind); } break; case SymbolKind.Property: break; case SymbolKind.Event: break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static void CheckForStructDefaultConstructors( ArrayBuilder<Symbol> members, bool isEnum, BindingDiagnosticBag diagnostics) { foreach (var s in members) { var m = s as MethodSymbol; if (!(m is null)) { if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0) { var location = m.Locations[0]; if (isEnum) { diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location); } else { MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location); if (m.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location); } } } } } } private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); if (builder.RecordDeclarationWithParameters is not null) { Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record && record.Kind() == SyntaxKind.RecordStructDeclaration); return; } foreach (var initializers in builder.InstanceInitializers) { foreach (FieldOrPropertyInitializer initializer in initializers) { var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt; MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]); } } } private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers) { var simpleProgramEntryPoints = GetSimpleProgramEntryPoints(); foreach (var member in simpleProgramEntryPoints) { builder.AddNonTypeMember(member, declaredMembersAndInitializers); } } private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct)) { return; } ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList; var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate(); var fieldsByName = PooledDictionary<string, Symbol>.GetInstance(); var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1); var memberNames = PooledHashSet<string>.GetInstance(); foreach (var member in membersSoFar) { memberNames.Add(member.Name); switch (member) { case EventSymbol: case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }: continue; case FieldSymbol { Name: var fieldName }: if (!fieldsByName.ContainsKey(fieldName)) { fieldsByName.Add(fieldName, member); } continue; } if (!memberSignatures.ContainsKey(member)) { memberSignatures.Add(member, member); } } CSharpCompilation compilation = this.DeclaringCompilation; bool isRecordClass = declaration.Kind == DeclarationKind.Record; // Positional record bool primaryAndCopyCtorAmbiguity = false; if (!(paramList is null)) { Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object); // primary ctor var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor; Debug.Assert(ctor is object); members.Add(ctor); if (ctor.ParameterCount != 0) { // properties and Deconstruct var existingOrAddedMembers = addProperties(ctor.Parameters); addDeconstruct(ctor, existingOrAddedMembers); } if (isRecordClass) { primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions); } } if (isRecordClass) { addCopyCtor(primaryAndCopyCtorAmbiguity); addCloneMethod(); } PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null; var thisEquals = addThisEquals(equalityContract); if (isRecordClass) { addBaseEquals(); } addObjectEquals(thisEquals); var getHashCode = addGetHashCode(equalityContract); addEqualityOperators(); if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode) { diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name); } var printMembers = addPrintMembersMethod(membersSoFar); addToStringMethod(printMembers); memberSignatures.Free(); fieldsByName.Free(); memberNames.Free(); // Synthesizing non-readonly properties in struct would require changing readonly logic for PrintMembers method synthesis Debug.Assert(isRecordClass || !members.Any(m => m is PropertySymbol { GetMethod.IsEffectivelyReadOnly: false })); // We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all // going to the record declaration members.AddRange(membersSoFar); builder.NonTypeMembers?.Free(); builder.NonTypeMembers = members; return; void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol)); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.DeconstructMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.Out )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod)) { members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics)); } else { var deconstruct = (MethodSymbol)existingDeconstructMethod; if (deconstruct.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct); } if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType); } if (deconstruct.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct); } } } void addCopyCtor(bool primaryAndCopyCtorAmbiguity) { Debug.Assert(isRecordClass); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.InstanceConstructorName, this, MethodKind.Constructor, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor)) { var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count); members.Add(copyCtor); if (primaryAndCopyCtorAmbiguity) { diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]); } } else { var constructor = (MethodSymbol)existingConstructor; if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor); } } } void addCloneMethod() { Debug.Assert(isRecordClass); members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics)); } MethodSymbol addPrintMembersMethod(IEnumerable<Symbol> userDefinedMembers) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.PrintMembersMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None)), RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); MethodSymbol printMembersMethod; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod)) { printMembersMethod = new SynthesizedRecordPrintMembers(this, userDefinedMembers, memberOffset: members.Count, diagnostics); members.Add(printMembersMethod); } else { printMembersMethod = (MethodSymbol)existingPrintMembersMethod; if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())) { if (printMembersMethod.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } } else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) { if (!printMembersMethod.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType); } } else if (isRecordClass) { SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics); } reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics); } return printMembersMethod; } void addToStringMethod(MethodSymbol printMethod) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectToString, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); var baseToStringMethod = getBaseToStringMethod(); if (baseToStringMethod is { IsSealed: true }) { if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord)) { var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion; var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion(); diagnostics.Add( ErrorCode.ERR_InheritingFromRecordWithSealedToString, this.Locations[0], languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } else { if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod)) { var toStringMethod = new SynthesizedRecordToString( this, printMethod, memberOffset: members.Count, isReadOnly: printMethod.IsEffectivelyReadOnly, diagnostics); members.Add(toStringMethod); } else { var toStringMethod = (MethodSymbol)existingToStringMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed) { MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability( diagnostics, this.DeclaringCompilation, toStringMethod.Locations[0]); } } } MethodSymbol? getBaseToStringMethod() { var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString); var currentBaseType = this.BaseTypeNoUseSiteDiagnostics; while (currentBaseType is not null) { foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString)) { if (member is not MethodSymbol method) continue; if (method.GetLeastOverriddenMethod(null) == objectToString) return method; } currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics; } return null; } } ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters) { var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length); int addedCount = 0; foreach (ParameterSymbol param in recordParameters) { bool isInherited = false; var syntax = param.GetNonNullSyntaxNode(); var targetProperty = new SignatureOnlyPropertySymbol(param.Name, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); if (!memberSignatures.TryGetValue(targetProperty, out var existingMember) && !fieldsByName.TryGetValue(param.Name, out existingMember)) { existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true); isInherited = true; } // There should be an error if we picked a member that is hidden // This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630 if (existingMember is null) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics)); } else if (existingMember is FieldSymbol { IsStatic: false } field && field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics); if (!isInherited || checkMemberNotHidden(field, param)) { existingOrAddedMembers.Add(field); } } else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop && prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { // There already exists a member corresponding to the candidate synthesized property. if (isInherited && prop.IsAbstract) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics)); } else if (!isInherited || checkMemberNotHidden(prop, param)) { // Deconstruct() is specified to simply assign from this property to the corresponding out parameter. existingOrAddedMembers.Add(prop); } } else { diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter, param.Locations[0], new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)), param.TypeWithAnnotations, param.Name); } void addProperty(SynthesizedRecordPropertySymbol property) { existingOrAddedMembers.Add(property); members.Add(property); Debug.Assert(property.GetMethod is object); Debug.Assert(property.SetMethod is object); members.Add(property.GetMethod); members.Add(property.SetMethod); members.Add(property.BackingField); builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal])); addedCount++; } } return existingOrAddedMembers.ToImmutableAndFree(); bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param) { if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name)) { diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol); return false; } return true; } } void addObjectEquals(MethodSymbol thisEquals) { members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics)); } MethodSymbol addGetHashCode(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectGetHashCode, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol getHashCode; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod)) { getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(getHashCode); } else { getHashCode = (MethodSymbol)existingHashCodeMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed) { diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode); } } return getHashCode; } PropertySymbol addEqualityContract() { Debug.Assert(isRecordClass); var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)), ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); PropertySymbol equalityContract; if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty)) { equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics); members.Add(equalityContract); members.Add(equalityContract.GetMethod); } else { equalityContract = (PropertySymbol)existingEqualityContractProperty; if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { if (equalityContract.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract); } } else if (equalityContract.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract); } if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions)) { if (!equalityContract.Type.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type); } } else { SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics); } if (equalityContract.GetMethod is null) { diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract); } reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics); } return equalityContract; } MethodSymbol addThisEquals(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectEquals, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol thisEquals; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod)) { thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(thisEquals); } else { thisEquals = (MethodSymbol)existingEqualsMethod; if (thisEquals.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals); } if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType); } reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics); } return thisEquals; } void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics) { if (isRecordClass && !IsSealed && ((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed)) { diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol); } else if (symbol.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol); } } void addBaseEquals() { Debug.Assert(isRecordClass); if (!BaseTypeNoUseSiteDiagnostics.IsObjectType()) { members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics)); } } void addEqualityOperators() { members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics)); members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics)); } } private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { //we're not calling the helpers on NamedTypeSymbol base, because those call //GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow) var hasInstanceConstructor = false; var hasParameterlessInstanceConstructor = false; var hasStaticConstructor = false; // CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the // dictionary construction process. For now, this is more encapsulated. var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); foreach (var member in membersSoFar) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; switch (method.MethodKind) { case MethodKind.Constructor: // Ignore the record copy constructor if (!IsRecord || !(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor)) { hasInstanceConstructor = true; hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0; } break; case MethodKind.StaticConstructor: hasStaticConstructor = true; break; } } //kick out early if we've seen everything we're looking for if (hasInstanceConstructor && hasStaticConstructor) { break; } } // NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor". // We won't insert a parameterless constructor for a struct if there already is one. // The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table. if ((!hasParameterlessInstanceConstructor && this.IsStructType()) || (!hasInstanceConstructor && !this.IsStatic && !this.IsInterface)) { builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ? new SynthesizedSubmissionConstructor(this, diagnostics) : new SynthesizedInstanceConstructor(this), declaredMembersAndInitializers); } // constants don't count, since they do not exist as fields at runtime // NOTE: even for decimal constants (which require field initializers), // we do not create .cctor here since a static constructor implicitly created for a decimal // should not appear in the list returned by public API like GetMembers(). if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers)) { // Note: we don't have to put anything in the method - the binder will // do that when processing field initializers. builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers); } if (this.IsScriptClass) { var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics); builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers); var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics); builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers); } static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst)); } } private void AddNonTypeMembers( DeclaredMembersAndInitializersBuilder builder, SyntaxList<MemberDeclarationSyntax> members, BindingDiagnosticBag diagnostics) { if (members.Count == 0) { return; } var firstMember = members[0]; var bodyBinder = this.GetBinder(firstMember); ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null; ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null; var compilation = DeclaringCompilation; foreach (var m in members) { if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } bool reportMisplacedGlobalCode = !m.HasErrors; switch (m.Kind()) { case SyntaxKind.FieldDeclaration: { var fieldSyntax = (FieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier)); } bool modifierErrors; var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors); foreach (var variable in fieldSyntax.Declaration.Variables) { var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0 ? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics) : new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics); builder.NonTypeMembers.Add(fieldSymbol); // All fields are included in the nullable context for constructors and initializers, even fields without // initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker. builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable); if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this, DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static), fieldSymbol); } if (variable.Initializer != null) { if (fieldSymbol.IsStatic) { AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer); } else { AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer); } } } } break; case SyntaxKind.MethodDeclaration: { var methodSyntax = (MethodDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(methodSyntax.Identifier)); } var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.ConstructorDeclaration: { var constructorSyntax = (ConstructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(constructorSyntax.Identifier)); } bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax); var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics); builder.NonTypeMembers.Add(constructor); if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer) { builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled); } } break; case SyntaxKind.DestructorDeclaration: { var destructorSyntax = (DestructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(destructorSyntax.Identifier)); } // CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the // runtime won't consider it a finalizer and it will not be marked as a destructor // when it is loaded from metadata. Perhaps we should just treat it as an Ordinary // method in such cases? var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics); builder.NonTypeMembers.Add(destructor); } break; case SyntaxKind.PropertyDeclaration: { var propertySyntax = (PropertyDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(propertySyntax.Identifier)); } var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics); builder.NonTypeMembers.Add(property); AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod); FieldSymbol backingField = property.BackingField; // TODO: can we leave this out of the member list? // From the 10/12/11 design notes: // In addition, we will change autoproperties to behavior in // a similar manner and make the autoproperty fields private. if ((object)backingField != null) { builder.NonTypeMembers.Add(backingField); builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax); var initializer = propertySyntax.Initializer; if (initializer != null) { if (IsScriptClass) { // also gather expression-declared variables from the initializer ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, initializer, this, DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0), backingField); } if (property.IsStatic) { AddInitializer(ref staticInitializers, backingField, initializer); } else { AddInitializer(ref instanceInitializers, backingField, initializer); } } } } break; case SyntaxKind.EventFieldDeclaration: { var eventFieldSyntax = (EventFieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add( ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier)); } foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables) { SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics); builder.NonTypeMembers.Add(@event); FieldSymbol? associatedField = @event.AssociatedField; if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this, DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0), associatedField); } if ((object?)associatedField != null) { // NOTE: specifically don't add the associated field to the members list // (regard it as an implementation detail). builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator); if (declarator.Initializer != null) { if (associatedField.IsStatic) { AddInitializer(ref staticInitializers, associatedField, declarator.Initializer); } else { AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer); } } } Debug.Assert((object)@event.AddMethod != null); Debug.Assert((object)@event.RemoveMethod != null); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); } } break; case SyntaxKind.EventDeclaration: { var eventSyntax = (EventDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventSyntax.Identifier)); } var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics); builder.NonTypeMembers.Add(@event); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); Debug.Assert(@event.AssociatedField is null); } break; case SyntaxKind.IndexerDeclaration: { var indexerSyntax = (IndexerDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(indexerSyntax.ThisKeyword)); } var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics); builder.HaveIndexers = true; builder.NonTypeMembers.Add(indexer); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod); } break; case SyntaxKind.ConversionOperatorDeclaration: { var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(conversionOperatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol( this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.OperatorDeclaration: { var operatorSyntax = (OperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(operatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol( this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.GlobalStatement: { var globalStatement = ((GlobalStatementSyntax)m).Statement; if (IsScriptClass) { var innerStatement = globalStatement; // drill into any LabeledStatements while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: // We shouldn't reach this place, but field declarations preceded with a label end up here. // This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now. var decl = (LocalDeclarationStatementSyntax)innerStatement; foreach (var vdecl in decl.Declaration.Variables) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private, containingFieldOpt: null); } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, innerStatement, this, DeclarationModifiers.Private, containingFieldOpt: null); break; default: // no other statement introduces variables into the enclosing scope break; } AddInitializer(ref instanceInitializers, null, globalStatement); } else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m)) { diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement)); } } break; default: Debug.Assert( SyntaxFacts.IsTypeDeclaration(m.Kind()) || m.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration or SyntaxKind.IncompleteMember); break; } } AddInitializers(builder.InstanceInitializers, instanceInitializers); AddInitializers(builder.StaticInitializers, staticInitializers); } private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt) { if (!(accessorOpt is null)) { symbols.Add(accessorOpt); } } internal override byte? GetLocalNullableContextValue() { byte? value; if (!_flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); _flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); var baseType = BaseTypeNoUseSiteDiagnostics; if (baseType is object) { builder.AddValue(TypeWithAnnotations.Create(baseType)); } foreach (var @interface in GetInterfacesToEmit()) { builder.AddValue(TypeWithAnnotations.Create(@interface)); } foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } foreach (var member in GetMembersUnordered()) { member.GetCommonNullableValues(compilation, ref builder); } // Not including lambdas or local functions. return builder.MostCommonValue; } /// <summary> /// Returns true if the overall nullable context is enabled for constructors and initializers. /// </summary> /// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param> internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic) { var membersAndInitializers = GetMembersAndInitializers(); return useStatic ? membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields : membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = DeclaringCompilation; NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (baseType is object) { if (baseType.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0)); } if (baseType.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType)); } if (baseType.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType)); } } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (baseType is object) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType))); } } } #endregion #region Extension Methods internal bool ContainsExtensionMethods { get { if (!_lazyContainsExtensionMethods.HasValue()) { bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods; _lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } } internal bool AnyMemberHasAttributes { get { if (!_lazyAnyMemberHasAttributes.HasValue()) { bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes; _lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState(); } return _lazyAnyMemberHasAttributes.Value(); } } public override bool MightContainExtensionMethods { get { return this.ContainsExtensionMethods; } } #endregion public sealed override NamedTypeSymbol ConstructedFrom { get { return this; } } internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0; internal class SynthesizedExplicitImplementations { public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty); public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods; public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls; private SynthesizedExplicitImplementations( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { ForwardingMethods = forwardingMethods.NullToEmpty(); MethodImpls = methodImpls.NullToEmpty(); } internal static SynthesizedExplicitImplementations Create( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty) { return Empty; } return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Represents a named type symbol whose members are declared in source. /// </summary> internal abstract partial class SourceMemberContainerTypeSymbol : NamedTypeSymbol { // The flags type is used to compact many different bits of information efficiently. private struct Flags { // We current pack everything into one 32-bit int; layout is given below. // // | |vvv|zzzz|f|d|yy|wwwwww| // // w = special type. 6 bits. // y = IsManagedType. 2 bits. // d = FieldDefinitionsNoted. 1 bit // f = FlattenedMembersIsSorted. 1 bit. // z = TypeKind. 4 bits. // v = NullableContext. 3 bits. private int _flags; private const int SpecialTypeOffset = 0; private const int SpecialTypeSize = 6; private const int ManagedKindOffset = SpecialTypeOffset + SpecialTypeSize; private const int ManagedKindSize = 2; private const int FieldDefinitionsNotedOffset = ManagedKindOffset + ManagedKindSize; private const int FieldDefinitionsNotedSize = 1; private const int FlattenedMembersIsSortedOffset = FieldDefinitionsNotedOffset + FieldDefinitionsNotedSize; private const int FlattenedMembersIsSortedSize = 1; private const int TypeKindOffset = FlattenedMembersIsSortedOffset + FlattenedMembersIsSortedSize; private const int TypeKindSize = 4; private const int NullableContextOffset = TypeKindOffset + TypeKindSize; private const int NullableContextSize = 3; private const int SpecialTypeMask = (1 << SpecialTypeSize) - 1; private const int ManagedKindMask = (1 << ManagedKindSize) - 1; private const int TypeKindMask = (1 << TypeKindSize) - 1; private const int NullableContextMask = (1 << NullableContextSize) - 1; private const int FieldDefinitionsNotedBit = 1 << FieldDefinitionsNotedOffset; private const int FlattenedMembersIsSortedBit = 1 << FlattenedMembersIsSortedOffset; public SpecialType SpecialType { get { return (SpecialType)((_flags >> SpecialTypeOffset) & SpecialTypeMask); } } public ManagedKind ManagedKind { get { return (ManagedKind)((_flags >> ManagedKindOffset) & ManagedKindMask); } } public bool FieldDefinitionsNoted { get { return (_flags & FieldDefinitionsNotedBit) != 0; } } // True if "lazyMembersFlattened" is sorted. public bool FlattenedMembersIsSorted { get { return (_flags & FlattenedMembersIsSortedBit) != 0; } } public TypeKind TypeKind { get { return (TypeKind)((_flags >> TypeKindOffset) & TypeKindMask); } } #if DEBUG static Flags() { // Verify masks are sufficient for values. Debug.Assert(EnumUtilities.ContainsAllValues<SpecialType>(SpecialTypeMask)); Debug.Assert(EnumUtilities.ContainsAllValues<NullableContextKind>(NullableContextMask)); } #endif public Flags(SpecialType specialType, TypeKind typeKind) { int specialTypeInt = ((int)specialType & SpecialTypeMask) << SpecialTypeOffset; int typeKindInt = ((int)typeKind & TypeKindMask) << TypeKindOffset; _flags = specialTypeInt | typeKindInt; } public void SetFieldDefinitionsNoted() { ThreadSafeFlagOperations.Set(ref _flags, FieldDefinitionsNotedBit); } public void SetFlattenedMembersIsSorted() { ThreadSafeFlagOperations.Set(ref _flags, (FlattenedMembersIsSortedBit)); } private static bool BitsAreUnsetOrSame(int bits, int mask) { return (bits & mask) == 0 || (bits & mask) == mask; } public void SetManagedKind(ManagedKind managedKind) { int bitsToSet = ((int)managedKind & ManagedKindMask) << ManagedKindOffset; Debug.Assert(BitsAreUnsetOrSame(_flags, bitsToSet)); ThreadSafeFlagOperations.Set(ref _flags, bitsToSet); } public bool TryGetNullableContext(out byte? value) { return ((NullableContextKind)((_flags >> NullableContextOffset) & NullableContextMask)).TryGetByte(out value); } public bool SetNullableContext(byte? value) { return ThreadSafeFlagOperations.Set(ref _flags, (((int)value.ToNullableContextFlags() & NullableContextMask) << NullableContextOffset)); } } private static readonly ObjectPool<PooledDictionary<Symbol, Symbol>> s_duplicateRecordMemberSignatureDictionary = PooledDictionary<Symbol, Symbol>.CreatePool(MemberSignatureComparer.RecordAPISignatureComparer); protected SymbolCompletionState state; private Flags _flags; private ImmutableArray<DiagnosticInfo> _managedKindUseSiteDiagnostics; private ImmutableArray<AssemblySymbol> _managedKindUseSiteDependencies; private readonly DeclarationModifiers _declModifiers; private readonly NamespaceOrTypeSymbol _containingSymbol; protected readonly MergedTypeDeclaration declaration; // The entry point symbol (resulting from top-level statements) is needed to construct non-type members because // it contributes to their binders, so we have to compute it first. // The value changes from "default" to "real value". The transition from "default" can only happen once. private ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> _lazySimpleProgramEntryPoints; // To compute explicitly declared members, binding must be limited (to avoid race conditions where binder cache captures symbols that aren't part of the final set) // The value changes from "uninitialized" to "real value" to null. The transition from "uninitialized" can only happen once. private DeclaredMembersAndInitializers? _lazyDeclaredMembersAndInitializers = DeclaredMembersAndInitializers.UninitializedSentinel; private MembersAndInitializers? _lazyMembersAndInitializers; private Dictionary<string, ImmutableArray<Symbol>>? _lazyMembersDictionary; private Dictionary<string, ImmutableArray<Symbol>>? _lazyEarlyAttributeDecodingMembersDictionary; private static readonly Dictionary<string, ImmutableArray<NamedTypeSymbol>> s_emptyTypeMembers = new Dictionary<string, ImmutableArray<NamedTypeSymbol>>(EmptyComparer.Instance); private Dictionary<string, ImmutableArray<NamedTypeSymbol>>? _lazyTypeMembers; private ImmutableArray<Symbol> _lazyMembersFlattened; private SynthesizedExplicitImplementations? _lazySynthesizedExplicitImplementations; private int _lazyKnownCircularStruct; private LexicalSortKey _lazyLexicalSortKey = LexicalSortKey.NotInitialized; private ThreeState _lazyContainsExtensionMethods; private ThreeState _lazyAnyMemberHasAttributes; #region Construction internal SourceMemberContainerTypeSymbol( NamespaceOrTypeSymbol containingSymbol, MergedTypeDeclaration declaration, BindingDiagnosticBag diagnostics, TupleExtraData? tupleData = null) : base(tupleData) { // If we're dealing with a simple program, then we must be in the global namespace Debug.Assert(containingSymbol is NamespaceSymbol { IsGlobalNamespace: true } || !declaration.Declarations.Any(d => d.IsSimpleProgram)); _containingSymbol = containingSymbol; this.declaration = declaration; TypeKind typeKind = declaration.Kind.ToTypeKind(); var modifiers = MakeModifiers(typeKind, diagnostics); foreach (var singleDeclaration in declaration.Declarations) { diagnostics.AddRange(singleDeclaration.Diagnostics); } int access = (int)(modifiers & DeclarationModifiers.AccessibilityMask); if ((access & (access - 1)) != 0) { // more than one access modifier if ((modifiers & DeclarationModifiers.Partial) != 0) diagnostics.Add(ErrorCode.ERR_PartialModifierConflict, Locations[0], this); access = access & ~(access - 1); // narrow down to one access modifier modifiers &= ~DeclarationModifiers.AccessibilityMask; // remove them all modifiers |= (DeclarationModifiers)access; // except the one } _declModifiers = modifiers; var specialType = access == (int)DeclarationModifiers.Public ? MakeSpecialType() : SpecialType.None; _flags = new Flags(specialType, typeKind); var containingType = this.ContainingType; if (containingType?.IsSealed == true && this.DeclaredAccessibility.HasProtected()) { diagnostics.Add(AccessCheck.GetProtectedMemberInSealedTypeError(ContainingType), Locations[0], this); } state.NotePartComplete(CompletionPart.TypeArguments); // type arguments need not be computed separately } private SpecialType MakeSpecialType() { // check if this is one of the COR library types if (ContainingSymbol.Kind == SymbolKind.Namespace && ContainingSymbol.ContainingAssembly.KeepLookingForDeclaredSpecialTypes) { //for a namespace, the emitted name is a dot-separated list of containing namespaces var emittedName = ContainingSymbol.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); emittedName = MetadataHelpers.BuildQualifiedName(emittedName, MetadataName); return SpecialTypes.GetTypeFromMetadataName(emittedName); } else { return SpecialType.None; } } private DeclarationModifiers MakeModifiers(TypeKind typeKind, BindingDiagnosticBag diagnostics) { Symbol containingSymbol = this.ContainingSymbol; DeclarationModifiers defaultAccess; var allowedModifiers = DeclarationModifiers.AccessibilityMask; if (containingSymbol.Kind == SymbolKind.Namespace) { defaultAccess = DeclarationModifiers.Internal; } else { allowedModifiers |= DeclarationModifiers.New; if (((NamedTypeSymbol)containingSymbol).IsInterface) { defaultAccess = DeclarationModifiers.Public; } else { defaultAccess = DeclarationModifiers.Private; } } switch (typeKind) { case TypeKind.Class: case TypeKind.Submission: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Sealed | DeclarationModifiers.Abstract | DeclarationModifiers.Unsafe; if (!this.IsRecord) { allowedModifiers |= DeclarationModifiers.Static; } break; case TypeKind.Struct: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.ReadOnly | DeclarationModifiers.Unsafe; if (!this.IsRecordStruct) { allowedModifiers |= DeclarationModifiers.Ref; } break; case TypeKind.Interface: allowedModifiers |= DeclarationModifiers.Partial | DeclarationModifiers.Unsafe; break; case TypeKind.Delegate: allowedModifiers |= DeclarationModifiers.Unsafe; break; } bool modifierErrors; var mods = MakeAndCheckTypeModifiers( defaultAccess, allowedModifiers, diagnostics, out modifierErrors); this.CheckUnsafeModifier(mods, diagnostics); if (!modifierErrors && (mods & DeclarationModifiers.Abstract) != 0 && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) != 0) { diagnostics.Add(ErrorCode.ERR_AbstractSealedStatic, Locations[0], this); } if (!modifierErrors && (mods & (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) == (DeclarationModifiers.Sealed | DeclarationModifiers.Static)) { diagnostics.Add(ErrorCode.ERR_SealedStaticClass, Locations[0], this); } switch (typeKind) { case TypeKind.Interface: mods |= DeclarationModifiers.Abstract; break; case TypeKind.Struct: case TypeKind.Enum: mods |= DeclarationModifiers.Sealed; break; case TypeKind.Delegate: mods |= DeclarationModifiers.Sealed; break; } return mods; } private DeclarationModifiers MakeAndCheckTypeModifiers( DeclarationModifiers defaultAccess, DeclarationModifiers allowedModifiers, BindingDiagnosticBag diagnostics, out bool modifierErrors) { modifierErrors = false; var result = DeclarationModifiers.Unset; var partCount = declaration.Declarations.Length; var missingPartial = false; for (var i = 0; i < partCount; i++) { var decl = declaration.Declarations[i]; var mods = decl.Modifiers; if (partCount > 1 && (mods & DeclarationModifiers.Partial) == 0) { missingPartial = true; } if (!modifierErrors) { mods = ModifierUtils.CheckModifiers( mods, allowedModifiers, declaration.Declarations[i].NameLocation, diagnostics, modifierTokens: null, modifierErrors: out modifierErrors); // It is an error for the same modifier to appear multiple times. if (!modifierErrors) { var info = ModifierUtils.CheckAccessibility(mods, this, isExplicitInterfaceImplementation: false); if (info != null) { diagnostics.Add(info, this.Locations[0]); modifierErrors = true; } } } if (result == DeclarationModifiers.Unset) { result = mods; } else { result |= mods; } } if ((result & DeclarationModifiers.AccessibilityMask) == 0) { result |= defaultAccess; } if (missingPartial) { if ((result & DeclarationModifiers.Partial) == 0) { // duplicate definitions switch (this.ContainingSymbol.Kind) { case SymbolKind.Namespace: for (var i = 1; i < partCount; i++) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInNS, declaration.Declarations[i].NameLocation, this.Name, this.ContainingSymbol); modifierErrors = true; } break; case SymbolKind.NamedType: for (var i = 1; i < partCount; i++) { if (ContainingType!.Locations.Length == 1 || ContainingType.IsPartial()) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, declaration.Declarations[i].NameLocation, this.ContainingSymbol, this.Name); modifierErrors = true; } break; } } else { for (var i = 0; i < partCount; i++) { var singleDeclaration = declaration.Declarations[i]; var mods = singleDeclaration.Modifiers; if ((mods & DeclarationModifiers.Partial) == 0) { diagnostics.Add(ErrorCode.ERR_MissingPartial, singleDeclaration.NameLocation, this.Name); modifierErrors = true; } } } } if (this.Name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword)) { foreach (var syntaxRef in SyntaxReferences) { SyntaxToken? identifier = syntaxRef.GetSyntax() switch { BaseTypeDeclarationSyntax typeDecl => typeDecl.Identifier, DelegateDeclarationSyntax delegateDecl => delegateDecl.Identifier, _ => null }; ReportTypeNamedRecord(identifier?.Text, this.DeclaringCompilation, diagnostics.DiagnosticBag, identifier?.GetLocation() ?? Location.None); } } return result; } internal static void ReportTypeNamedRecord(string? name, CSharpCompilation compilation, DiagnosticBag? diagnostics, Location location) { if (diagnostics is object && name == SyntaxFacts.GetText(SyntaxKind.RecordKeyword) && compilation.LanguageVersion >= MessageID.IDS_FeatureRecords.RequiredVersion()) { diagnostics.Add(ErrorCode.WRN_RecordNamedDisallowed, location, name); } } #endregion #region Completion internal sealed override bool RequiresCompletion { get { return true; } } internal sealed override bool HasComplete(CompletionPart part) { return state.HasComplete(part); } protected abstract void CheckBase(BindingDiagnosticBag diagnostics); protected abstract void CheckInterfaces(BindingDiagnosticBag diagnostics); internal override void ForceComplete(SourceLocation? locationOpt, CancellationToken cancellationToken) { while (true) { // NOTE: cases that depend on GetMembers[ByName] should call RequireCompletionPartMembers. cancellationToken.ThrowIfCancellationRequested(); var incompletePart = state.NextIncompletePart; switch (incompletePart) { case CompletionPart.Attributes: GetAttributes(); break; case CompletionPart.StartBaseType: case CompletionPart.FinishBaseType: if (state.NotePartComplete(CompletionPart.StartBaseType)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckBase(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishBaseType); diagnostics.Free(); } break; case CompletionPart.StartInterfaces: case CompletionPart.FinishInterfaces: if (state.NotePartComplete(CompletionPart.StartInterfaces)) { var diagnostics = BindingDiagnosticBag.GetInstance(); CheckInterfaces(diagnostics); AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.FinishInterfaces); diagnostics.Free(); } break; case CompletionPart.EnumUnderlyingType: var discarded = this.EnumUnderlyingType; break; case CompletionPart.TypeArguments: { var tmp = this.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics; // force type arguments } break; case CompletionPart.TypeParameters: // force type parameters foreach (var typeParameter in this.TypeParameters) { typeParameter.ForceComplete(locationOpt, cancellationToken); } state.NotePartComplete(CompletionPart.TypeParameters); break; case CompletionPart.Members: this.GetMembersByName(); break; case CompletionPart.TypeMembers: this.GetTypeMembersUnordered(); break; case CompletionPart.SynthesizedExplicitImplementations: this.GetSynthesizedExplicitImplementations(cancellationToken); //force interface and base class errors to be checked break; case CompletionPart.StartMemberChecks: case CompletionPart.FinishMemberChecks: if (state.NotePartComplete(CompletionPart.StartMemberChecks)) { var diagnostics = BindingDiagnosticBag.GetInstance(); AfterMembersChecks(diagnostics); AddDeclarationDiagnostics(diagnostics); // We may produce a SymbolDeclaredEvent for the enclosing type before events for its contained members DeclaringCompilation.SymbolDeclaredEvent(this); var thisThreadCompleted = state.NotePartComplete(CompletionPart.FinishMemberChecks); Debug.Assert(thisThreadCompleted); diagnostics.Free(); } break; case CompletionPart.MembersCompleted: { ImmutableArray<Symbol> members = this.GetMembersUnordered(); bool allCompleted = true; if (locationOpt == null) { foreach (var member in members) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } else { foreach (var member in members) { ForceCompleteMemberByLocation(locationOpt, member, cancellationToken); allCompleted = allCompleted && member.HasComplete(CompletionPart.All); } } if (!allCompleted) { // We did not complete all members so we won't have enough information for // the PointedAtManagedTypeChecks, so just kick out now. var allParts = CompletionPart.NamedTypeSymbolWithLocationAll; state.SpinWaitComplete(allParts, cancellationToken); return; } EnsureFieldDefinitionsNoted(); // We've completed all members, so we're ready for the PointedAtManagedTypeChecks; // proceed to the next iteration. state.NotePartComplete(CompletionPart.MembersCompleted); break; } case CompletionPart.None: return; default: // This assert will trigger if we forgot to handle any of the completion parts Debug.Assert((incompletePart & CompletionPart.NamedTypeSymbolAll) == 0); // any other values are completion parts intended for other kinds of symbols state.NotePartComplete(CompletionPart.All & ~CompletionPart.NamedTypeSymbolAll); break; } state.SpinWaitComplete(incompletePart, cancellationToken); } throw ExceptionUtilities.Unreachable; } internal void EnsureFieldDefinitionsNoted() { if (_flags.FieldDefinitionsNoted) { return; } NoteFieldDefinitions(); } private void NoteFieldDefinitions() { // we must note all fields once therefore we need to lock var membersAndInitializers = this.GetMembersAndInitializers(); lock (membersAndInitializers) { if (!_flags.FieldDefinitionsNoted) { var assembly = (SourceAssemblySymbol)ContainingAssembly; Accessibility containerEffectiveAccessibility = EffectiveAccessibility(); foreach (var member in membersAndInitializers.NonTypeMembers) { FieldSymbol field; if (!member.IsFieldOrFieldLikeEvent(out field) || field.IsConst || field.IsFixedSizeBuffer) { continue; } Accessibility fieldDeclaredAccessibility = field.DeclaredAccessibility; if (fieldDeclaredAccessibility == Accessibility.Private) { // mark private fields as tentatively unassigned and unread unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: true); } else if (containerEffectiveAccessibility == Accessibility.Private) { // mark effectively private fields as tentatively unassigned unless we discover otherwise. assembly.NoteFieldDefinition(field, isInternal: false, isUnread: false); } else if (fieldDeclaredAccessibility == Accessibility.Internal || containerEffectiveAccessibility == Accessibility.Internal) { // mark effectively internal fields as tentatively unassigned unless we discover otherwise. // NOTE: These fields will be reported as unassigned only if internals are not visible from this assembly. // See property SourceAssemblySymbol.UnusedFieldWarnings. assembly.NoteFieldDefinition(field, isInternal: true, isUnread: false); } } _flags.SetFieldDefinitionsNoted(); } } } #endregion #region Containers public sealed override NamedTypeSymbol? ContainingType { get { return _containingSymbol as NamedTypeSymbol; } } public sealed override Symbol ContainingSymbol { get { return _containingSymbol; } } #endregion #region Flags Encoded Properties public override SpecialType SpecialType { get { return _flags.SpecialType; } } public override TypeKind TypeKind { get { return _flags.TypeKind; } } internal MergedTypeDeclaration MergedDeclaration { get { return this.declaration; } } internal sealed override bool IsInterface { get { // TypeKind is computed eagerly, so this is cheap. return this.TypeKind == TypeKind.Interface; } } internal override ManagedKind GetManagedKind(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { var managedKind = _flags.ManagedKind; if (managedKind == ManagedKind.Unknown) { var managedKindUseSiteInfo = new CompoundUseSiteInfo<AssemblySymbol>(ContainingAssembly); managedKind = base.GetManagedKind(ref managedKindUseSiteInfo); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDiagnostics, managedKindUseSiteInfo.Diagnostics?.ToImmutableArray() ?? ImmutableArray<DiagnosticInfo>.Empty); ImmutableInterlocked.InterlockedInitialize(ref _managedKindUseSiteDependencies, managedKindUseSiteInfo.Dependencies?.ToImmutableArray() ?? ImmutableArray<AssemblySymbol>.Empty); _flags.SetManagedKind(managedKind); } if (useSiteInfo.AccumulatesDiagnostics) { ImmutableArray<DiagnosticInfo> useSiteDiagnostics = _managedKindUseSiteDiagnostics; // Ensure we have the latest value from the field useSiteDiagnostics = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDiagnostics, useSiteDiagnostics, useSiteDiagnostics); Debug.Assert(!useSiteDiagnostics.IsDefault); useSiteInfo.AddDiagnostics(useSiteDiagnostics); } if (useSiteInfo.AccumulatesDependencies) { ImmutableArray<AssemblySymbol> useSiteDependencies = _managedKindUseSiteDependencies; // Ensure we have the latest value from the field useSiteDependencies = ImmutableInterlocked.InterlockedCompareExchange(ref _managedKindUseSiteDependencies, useSiteDependencies, useSiteDependencies); Debug.Assert(!useSiteDependencies.IsDefault); useSiteInfo.AddDependencies(useSiteDependencies); } return managedKind; } public override bool IsStatic => HasFlag(DeclarationModifiers.Static); public sealed override bool IsRefLikeType => HasFlag(DeclarationModifiers.Ref); public override bool IsReadOnly => HasFlag(DeclarationModifiers.ReadOnly); public override bool IsSealed => HasFlag(DeclarationModifiers.Sealed); public override bool IsAbstract => HasFlag(DeclarationModifiers.Abstract); internal bool IsPartial => HasFlag(DeclarationModifiers.Partial); internal bool IsNew => HasFlag(DeclarationModifiers.New); [MethodImpl(MethodImplOptions.AggressiveInlining)] private bool HasFlag(DeclarationModifiers flag) => (_declModifiers & flag) != 0; public override Accessibility DeclaredAccessibility { get { return ModifierUtils.EffectiveAccessibility(_declModifiers); } } /// <summary> /// Compute the "effective accessibility" of the current class for the purpose of warnings about unused fields. /// </summary> private Accessibility EffectiveAccessibility() { var result = DeclaredAccessibility; if (result == Accessibility.Private) return Accessibility.Private; for (Symbol? container = this.ContainingType; !(container is null); container = container.ContainingType) { switch (container.DeclaredAccessibility) { case Accessibility.Private: return Accessibility.Private; case Accessibility.Internal: result = Accessibility.Internal; continue; } } return result; } #endregion #region Syntax public override bool IsScriptClass { get { var kind = this.declaration.Declarations[0].Kind; return kind == DeclarationKind.Script || kind == DeclarationKind.Submission; } } public override bool IsImplicitClass { get { return this.declaration.Declarations[0].Kind == DeclarationKind.ImplicitClass; } } internal override bool IsRecord { get { return this.declaration.Declarations[0].Kind == DeclarationKind.Record; } } internal override bool IsRecordStruct { get { return this.declaration.Declarations[0].Kind == DeclarationKind.RecordStruct; } } public override bool IsImplicitlyDeclared { get { return IsImplicitClass || IsScriptClass; } } public override int Arity { get { return declaration.Arity; } } public override string Name { get { return declaration.Name; } } internal override bool MangleName { get { return Arity > 0; } } internal override LexicalSortKey GetLexicalSortKey() { if (!_lazyLexicalSortKey.IsInitialized) { _lazyLexicalSortKey.SetFrom(declaration.GetLexicalSortKey(this.DeclaringCompilation)); } return _lazyLexicalSortKey; } public sealed override ImmutableArray<Location> Locations { get { return declaration.NameLocations.Cast<SourceLocation, Location>(); } } public ImmutableArray<SyntaxReference> SyntaxReferences { get { return this.declaration.SyntaxReferences; } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return SyntaxReferences; } } // This method behaves the same was as the base class, but avoids allocations associated with DeclaringSyntaxReferences internal override bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken) { var declarations = declaration.Declarations; if (IsImplicitlyDeclared && declarations.IsEmpty) { return ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var declaration in declarations) { cancellationToken.ThrowIfCancellationRequested(); var syntaxRef = declaration.SyntaxReference; if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } #endregion #region Members /// <summary> /// Encapsulates information about the non-type members of a (i.e. this) type. /// 1) For non-initializers, symbols are created and stored in a list. /// 2) For fields and properties/indexers, the symbols are stored in (1) and their initializers are /// stored with other initialized fields and properties from the same syntax tree with /// the same static-ness. /// </summary> protected sealed class MembersAndInitializers { internal readonly ImmutableArray<Symbol> NonTypeMembers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; internal readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; internal readonly bool HaveIndexers; internal readonly bool IsNullableEnabledForInstanceConstructorsAndFields; internal readonly bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields) { Debug.Assert(!nonTypeMembers.IsDefault); Debug.Assert(!staticInitializers.IsDefault); Debug.Assert(staticInitializers.All(g => !g.IsDefault)); Debug.Assert(!instanceInitializers.IsDefault); Debug.Assert(instanceInitializers.All(g => !g.IsDefault)); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(haveIndexers == nonTypeMembers.Any(s => s.IsIndexer())); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers { get { return GetMembersAndInitializers().StaticInitializers; } } internal ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers { get { return GetMembersAndInitializers().InstanceInitializers; } } internal int CalculateSyntaxOffsetInSynthesizedConstructor(int position, SyntaxTree tree, bool isStatic) { if (IsScriptClass && !isStatic) { int aggregateLength = 0; foreach (var declaration in this.declaration.Declarations) { var syntaxRef = declaration.SyntaxReference; if (tree == syntaxRef.SyntaxTree) { return aggregateLength + position; } aggregateLength += syntaxRef.Span.Length; } throw ExceptionUtilities.Unreachable; } int syntaxOffset; if (TryCalculateSyntaxOffsetOfPositionInInitializer(position, tree, isStatic, ctorInitializerLength: 0, syntaxOffset: out syntaxOffset)) { return syntaxOffset; } if (declaration.Declarations.Length >= 1 && position == declaration.Declarations[0].Location.SourceSpan.Start) { // With dynamic analysis instrumentation, the introducing declaration of a type can provide // the syntax associated with both the analysis payload local of a synthesized constructor // and with the constructor itself. If the synthesized constructor includes an initializer with a lambda, // that lambda needs a closure that captures the analysis payload of the constructor, // and the offset of the syntax for the local within the constructor is by definition zero. return 0; } // an implicit constructor has no body and no initializer, so the variable has to be declared in a member initializer throw ExceptionUtilities.Unreachable; } /// <summary> /// Calculates a syntax offset of a syntax position that is contained in a property or field initializer (if it is in fact contained in one). /// </summary> internal bool TryCalculateSyntaxOffsetOfPositionInInitializer(int position, SyntaxTree tree, bool isStatic, int ctorInitializerLength, out int syntaxOffset) { Debug.Assert(ctorInitializerLength >= 0); var membersAndInitializers = GetMembersAndInitializers(); var allInitializers = isStatic ? membersAndInitializers.StaticInitializers : membersAndInitializers.InstanceInitializers; if (!findInitializer(allInitializers, position, tree, out FieldOrPropertyInitializer initializer, out int precedingLength)) { syntaxOffset = 0; return false; } // |<-----------distanceFromCtorBody----------->| // [ initializer 0 ][ initializer 1 ][ initializer 2 ][ctor initializer][ctor body] // |<--preceding init len-->| ^ // position int initializersLength = getInitializersLength(allInitializers); int distanceFromInitializerStart = position - initializer.Syntax.Span.Start; int distanceFromCtorBody = initializersLength + ctorInitializerLength - (precedingLength + distanceFromInitializerStart); Debug.Assert(distanceFromCtorBody > 0); // syntax offset 0 is at the start of the ctor body: syntaxOffset = -distanceFromCtorBody; return true; static bool findInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, int position, SyntaxTree tree, out FieldOrPropertyInitializer found, out int precedingLength) { precedingLength = 0; foreach (var group in initializers) { if (!group.IsEmpty && group[0].Syntax.SyntaxTree == tree && position < group.Last().Syntax.Span.End) { // Found group of interest var initializerIndex = IndexOfInitializerContainingPosition(group, position); if (initializerIndex < 0) { break; } precedingLength += getPrecedingInitializersLength(group, initializerIndex); found = group[initializerIndex]; return true; } precedingLength += getGroupLength(group); } found = default; return false; } static int getGroupLength(ImmutableArray<FieldOrPropertyInitializer> initializers) { int length = 0; foreach (var initializer in initializers) { length += getInitializerLength(initializer); } return length; } static int getPrecedingInitializersLength(ImmutableArray<FieldOrPropertyInitializer> initializers, int index) { int length = 0; for (var i = 0; i < index; i++) { length += getInitializerLength(initializers[i]); } return length; } static int getInitializersLength(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { int length = 0; foreach (var group in initializers) { length += getGroupLength(group); } return length; } static int getInitializerLength(FieldOrPropertyInitializer initializer) { // A constant field of type decimal needs a field initializer, so // check if it is a metadata constant, not just a constant to exclude // decimals. Other constants do not need field initializers. if (initializer.FieldOpt == null || !initializer.FieldOpt.IsMetadataConstant) { // ignore leading and trailing trivia of the node: return initializer.Syntax.Span.Length; } return 0; } } private static int IndexOfInitializerContainingPosition(ImmutableArray<FieldOrPropertyInitializer> initializers, int position) { // Search for the start of the span (the spans are non-overlapping and sorted) int index = initializers.BinarySearch(position, (initializer, pos) => initializer.Syntax.Span.Start.CompareTo(pos)); // Binary search returns non-negative result if the position is exactly the start of some span. if (index >= 0) { return index; } // Otherwise, ~index is the closest span whose start is greater than the position. // => Check if the preceding initializer span contains the position. int precedingInitializerIndex = ~index - 1; if (precedingInitializerIndex >= 0 && initializers[precedingInitializerIndex].Syntax.Span.Contains(position)) { return precedingInitializerIndex; } return -1; } public override IEnumerable<string> MemberNames { get { return (IsTupleType || IsRecord || IsRecordStruct) ? GetMembers().Select(m => m.Name) : this.declaration.MemberNames; } } internal override ImmutableArray<NamedTypeSymbol> GetTypeMembersUnordered() { return GetTypeMembersDictionary().Flatten(); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers() { return GetTypeMembersDictionary().Flatten(LexicalOrderSymbolComparer.Instance); } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name) { ImmutableArray<NamedTypeSymbol> members; if (GetTypeMembersDictionary().TryGetValue(name, out members)) { return members; } return ImmutableArray<NamedTypeSymbol>.Empty; } public override ImmutableArray<NamedTypeSymbol> GetTypeMembers(string name, int arity) { return GetTypeMembers(name).WhereAsArray((t, arity) => t.Arity == arity, arity); } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> GetTypeMembersDictionary() { if (_lazyTypeMembers == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); if (Interlocked.CompareExchange(ref _lazyTypeMembers, MakeTypeMembers(diagnostics), null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.TypeMembers); } diagnostics.Free(); } return _lazyTypeMembers; } private Dictionary<string, ImmutableArray<NamedTypeSymbol>> MakeTypeMembers(BindingDiagnosticBag diagnostics) { var symbols = ArrayBuilder<NamedTypeSymbol>.GetInstance(); var conflictDict = new Dictionary<(string, int), SourceNamedTypeSymbol>(); try { foreach (var childDeclaration in declaration.Children) { var t = new SourceNamedTypeSymbol(this, childDeclaration, diagnostics); this.CheckMemberNameDistinctFromType(t, diagnostics); var key = (t.Name, t.Arity); SourceNamedTypeSymbol? other; if (conflictDict.TryGetValue(key, out other)) { if (Locations.Length == 1 || IsPartial) { if (t.IsPartial && other.IsPartial) { diagnostics.Add(ErrorCode.ERR_PartialTypeKindConflict, t.Locations[0], t); } else { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, t.Locations[0], this, t.Name); } } } else { conflictDict.Add(key, t); } symbols.Add(t); } if (IsInterface) { foreach (var t in symbols) { Binder.CheckFeatureAvailability(t.DeclaringSyntaxReferences[0].GetSyntax(), MessageID.IDS_DefaultInterfaceImplementation, diagnostics, t.Locations[0]); } } Debug.Assert(s_emptyTypeMembers.Count == 0); return symbols.Count > 0 ? symbols.ToDictionary(s => s.Name, StringOrdinalComparer.Instance) : s_emptyTypeMembers; } finally { symbols.Free(); } } private void CheckMemberNameDistinctFromType(Symbol member, BindingDiagnosticBag diagnostics) { switch (this.TypeKind) { case TypeKind.Class: case TypeKind.Struct: if (member.Name == this.Name) { diagnostics.Add(ErrorCode.ERR_MemberNameSameAsType, member.Locations[0], this.Name); } break; case TypeKind.Interface: if (member.IsStatic) { goto case TypeKind.Class; } break; } } internal override ImmutableArray<Symbol> GetMembersUnordered() { var result = _lazyMembersFlattened; if (result.IsDefault) { result = GetMembersByName().Flatten(null); // do not sort. ImmutableInterlocked.InterlockedInitialize(ref _lazyMembersFlattened, result); result = _lazyMembersFlattened; } return result.ConditionallyDeOrder(); } public override ImmutableArray<Symbol> GetMembers() { if (_flags.FlattenedMembersIsSorted) { return _lazyMembersFlattened; } else { var allMembers = this.GetMembersUnordered(); if (allMembers.Length > 1) { // The array isn't sorted. Sort it and remember that we sorted it. allMembers = allMembers.Sort(LexicalOrderSymbolComparer.Instance); ImmutableInterlocked.InterlockedExchange(ref _lazyMembersFlattened, allMembers); } _flags.SetFlattenedMembersIsSorted(); return allMembers; } } public sealed override ImmutableArray<Symbol> GetMembers(string name) { ImmutableArray<Symbol> members; if (GetMembersByName().TryGetValue(name, out members)) { return members; } return ImmutableArray<Symbol>.Empty; } /// <remarks> /// For source symbols, there can only be a valid clone method if this is a record, which is a /// simple syntax check. This will need to change when we generalize cloning, but it's a good /// heuristic for now. /// </remarks> internal override bool HasPossibleWellKnownCloneMethod() => IsRecord; internal override ImmutableArray<Symbol> GetSimpleNonTypeMembers(string name) { if (_lazyMembersDictionary != null || declaration.MemberNames.Contains(name) || declaration.Kind is DeclarationKind.Record or DeclarationKind.RecordStruct) { return GetMembers(name); } return ImmutableArray<Symbol>.Empty; } internal override IEnumerable<FieldSymbol> GetFieldsToEmit() { if (this.TypeKind == TypeKind.Enum) { // For consistency with Dev10, emit value__ field first. var valueField = ((SourceNamedTypeSymbol)this).EnumValueField; RoslynDebug.Assert((object)valueField != null); yield return valueField; } foreach (var m in this.GetMembers()) { switch (m.Kind) { case SymbolKind.Field: if (m is TupleErrorFieldSymbol) { break; } yield return (FieldSymbol)m; break; case SymbolKind.Event: FieldSymbol? associatedField = ((EventSymbol)m).AssociatedField; if ((object?)associatedField != null) { yield return associatedField; } break; } } } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers() { return GetEarlyAttributeDecodingMembersDictionary().Flatten(); } /// <summary> /// During early attribute decoding, we consider a safe subset of all members that will not /// cause cyclic dependencies. Get all such members for this symbol that have a particular name. /// /// In particular, this method will return nested types and fields (other than auto-property /// backing fields). /// </summary> internal override ImmutableArray<Symbol> GetEarlyAttributeDecodingMembers(string name) { ImmutableArray<Symbol> result; return GetEarlyAttributeDecodingMembersDictionary().TryGetValue(name, out result) ? result : ImmutableArray<Symbol>.Empty; } private Dictionary<string, ImmutableArray<Symbol>> GetEarlyAttributeDecodingMembersDictionary() { if (_lazyEarlyAttributeDecodingMembersDictionary == null) { if (Volatile.Read(ref _lazyMembersDictionary) is Dictionary<string, ImmutableArray<Symbol>> result) { return result; } var membersAndInitializers = GetMembersAndInitializers(); //NOTE: separately cached // NOTE: members were added in a single pass over the syntax, so they're already // in lexical order. Dictionary<string, ImmutableArray<Symbol>> membersByName; if (!membersAndInitializers.HaveIndexers) { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name); } else { // We can't include indexer symbol yet, because we don't know // what name it will have after attribute binding (because of // IndexerNameAttribute). membersByName = membersAndInitializers.NonTypeMembers. WhereAsArray(s => !s.IsIndexer() && (!s.IsAccessor() || ((MethodSymbol)s).AssociatedSymbol?.IsIndexer() != true)). ToDictionary(s => s.Name); } AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); Interlocked.CompareExchange(ref _lazyEarlyAttributeDecodingMembersDictionary, membersByName, null); } return _lazyEarlyAttributeDecodingMembersDictionary; } // NOTE: this method should do as little work as possible // we often need to get members just to do a lookup. // All additional checks and diagnostics may be not // needed yet or at all. protected MembersAndInitializers GetMembersAndInitializers() { var membersAndInitializers = _lazyMembersAndInitializers; if (membersAndInitializers != null) { return membersAndInitializers; } var diagnostics = BindingDiagnosticBag.GetInstance(); membersAndInitializers = BuildMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyMembersAndInitializers, membersAndInitializers, null); if (alreadyKnown != null) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); _lazyDeclaredMembersAndInitializers = null; return membersAndInitializers!; } /// <summary> /// The purpose of this function is to assert that the <paramref name="member"/> symbol /// is actually among the symbols cached by this type symbol in a way that ensures /// that any consumer of standard APIs to get to type's members is going to get the same /// symbol (same instance) for the member rather than an equivalent, but different instance. /// </summary> [Conditional("DEBUG")] internal void AssertMemberExposure(Symbol member, bool forDiagnostics = false) { if (member is FieldSymbol && forDiagnostics && this.IsTupleType) { // There is a problem with binding types of fields in tuple types. // Skipping verification for them temporarily. return; } if (member is NamedTypeSymbol type) { RoslynDebug.AssertOrFailFast(forDiagnostics); RoslynDebug.AssertOrFailFast(Volatile.Read(ref _lazyTypeMembers)?.Values.Any(types => types.Contains(t => t == (object)type)) == true); return; } else if (member is TypeParameterSymbol || member is SynthesizedMethodBaseSymbol) { RoslynDebug.AssertOrFailFast(forDiagnostics); return; } else if (member is FieldSymbol field && field.AssociatedSymbol is EventSymbol e) { RoslynDebug.AssertOrFailFast(forDiagnostics); // Backing fields for field-like events are not added to the members list. member = e; } var membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } if (membersAndInitializers is null) { if (member is SynthesizedSimpleProgramEntryPointSymbol) { RoslynDebug.AssertOrFailFast(GetSimpleProgramEntryPoints().Contains(m => m == (object)member)); return; } var declared = Volatile.Read(ref _lazyDeclaredMembersAndInitializers); RoslynDebug.AssertOrFailFast(declared != DeclaredMembersAndInitializers.UninitializedSentinel); if (declared is object) { if (declared.NonTypeMembers.Contains(m => m == (object)member) || declared.RecordPrimaryConstructor == (object)member) { return; } } else { // It looks like there was a race and we need to check _lazyMembersAndInitializers again membersAndInitializers = Volatile.Read(ref _lazyMembersAndInitializers); RoslynDebug.AssertOrFailFast(membersAndInitializers is object); if (isMemberInCompleteMemberList(membersAndInitializers, member)) { return; } } } RoslynDebug.AssertOrFailFast(false, "Premature symbol exposure."); static bool isMemberInCompleteMemberList(MembersAndInitializers? membersAndInitializers, Symbol member) { return membersAndInitializers?.NonTypeMembers.Contains(m => m == (object)member) == true; } } protected Dictionary<string, ImmutableArray<Symbol>> GetMembersByName() { if (this.state.HasComplete(CompletionPart.Members)) { return _lazyMembersDictionary!; } return GetMembersByNameSlow(); } private Dictionary<string, ImmutableArray<Symbol>> GetMembersByNameSlow() { if (_lazyMembersDictionary == null) { var diagnostics = BindingDiagnosticBag.GetInstance(); var membersDictionary = MakeAllMembers(diagnostics); if (Interlocked.CompareExchange(ref _lazyMembersDictionary, membersDictionary, null) == null) { AddDeclarationDiagnostics(diagnostics); state.NotePartComplete(CompletionPart.Members); } diagnostics.Free(); } state.SpinWaitComplete(CompletionPart.Members, default(CancellationToken)); return _lazyMembersDictionary; } internal override IEnumerable<Symbol> GetInstanceFieldsAndEvents() { var membersAndInitializers = this.GetMembersAndInitializers(); return membersAndInitializers.NonTypeMembers.Where(IsInstanceFieldOrEvent); } protected void AfterMembersChecks(BindingDiagnosticBag diagnostics) { if (IsInterface) { CheckInterfaceMembers(this.GetMembersAndInitializers().NonTypeMembers, diagnostics); } CheckMemberNamesDistinctFromType(diagnostics); CheckMemberNameConflicts(diagnostics); CheckRecordMemberNames(diagnostics); CheckSpecialMemberErrors(diagnostics); CheckTypeParameterNameConflicts(diagnostics); CheckAccessorNameConflicts(diagnostics); bool unused = KnownCircularStruct; CheckSequentialOnPartialType(diagnostics); CheckForProtectedInStaticClass(diagnostics); CheckForUnmatchedOperators(diagnostics); var location = Locations[0]; var compilation = DeclaringCompilation; if (this.IsRefLikeType) { compilation.EnsureIsByRefLikeAttributeExists(diagnostics, location, modifyCompilation: true); } if (this.IsReadOnly) { compilation.EnsureIsReadOnlyAttributeExists(diagnostics, location, modifyCompilation: true); } var baseType = BaseTypeNoUseSiteDiagnostics; var interfaces = GetInterfacesToEmit(); // https://github.com/dotnet/roslyn/issues/30080: Report diagnostics for base type and interfaces at more specific locations. if (hasBaseTypeOrInterface(t => t.ContainsNativeInteger())) { compilation.EnsureNativeIntegerAttributeExists(diagnostics, location, modifyCompilation: true); } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out _)) { compilation.EnsureNullableContextAttributeExists(diagnostics, location, modifyCompilation: true); } if (hasBaseTypeOrInterface(t => t.NeedsNullableAttribute())) { compilation.EnsureNullableAttributeExists(diagnostics, location, modifyCompilation: true); } } if (interfaces.Any(t => needsTupleElementNamesAttribute(t))) { // Note: we don't need to check base type or directly implemented interfaces (which will be reported during binding) // so the checking of all interfaces here involves some redundancy. Binder.ReportMissingTupleElementNamesAttributesIfNeeded(compilation, location, diagnostics); } bool hasBaseTypeOrInterface(Func<NamedTypeSymbol, bool> predicate) { return ((object)baseType != null && predicate(baseType)) || interfaces.Any(predicate); } static bool needsTupleElementNamesAttribute(TypeSymbol type) { if (type is null) { return false; } var resultType = type.VisitType( predicate: (t, a, b) => !t.TupleElementNames.IsDefaultOrEmpty && !t.IsErrorType(), arg: (object?)null); return resultType is object; } } private void CheckMemberNamesDistinctFromType(BindingDiagnosticBag diagnostics) { foreach (var member in GetMembersAndInitializers().NonTypeMembers) { CheckMemberNameDistinctFromType(member, diagnostics); } } private void CheckRecordMemberNames(BindingDiagnosticBag diagnostics) { if (declaration.Kind != DeclarationKind.Record && declaration.Kind != DeclarationKind.RecordStruct) { return; } foreach (var member in GetMembers("Clone")) { diagnostics.Add(ErrorCode.ERR_CloneDisallowedInRecord, member.Locations[0]); } } private void CheckMemberNameConflicts(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName = GetMembersByName(); // Collisions involving indexers are handled specially. CheckIndexerNameConflicts(diagnostics, membersByName); // key and value will be the same object in these dictionaries. var methodsBySignature = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsMethods = new Dictionary<SourceMemberMethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.DuplicateSourceComparer); var conversionsAsConversions = new HashSet<SourceUserDefinedConversionSymbol>(ConversionSignatureComparer.Comparer); // SPEC: The signature of an operator must differ from the signatures of all other // SPEC: operators declared in the same class. // DELIBERATE SPEC VIOLATION: // The specification does not state that a user-defined conversion reserves the names // op_Implicit or op_Explicit, but nevertheless the native compiler does so; an attempt // to define a field or a conflicting method with the metadata name of a user-defined // conversion is an error. We preserve this reasonable behavior. // // Similarly, we treat "public static C operator +(C, C)" as colliding with // "public static C op_Addition(C, C)". Fortunately, this behavior simply // falls out of treating user-defined operators as ordinary methods; we do // not need any special handling in this method. // // However, we must have special handling for conversions because conversions // use a completely different rule for detecting collisions between two // conversions: conversion signatures consist only of the source and target // types of the conversions, and not the kind of the conversion (implicit or explicit), // the name of the method, and so on. // // Therefore we must detect the following kinds of member name conflicts: // // 1. a method, conversion or field has the same name as a (different) field (* see note below) // 2. a method has the same method signature as another method or conversion // 3. a conversion has the same conversion signature as another conversion. // // However, we must *not* detect "a conversion has the same *method* signature // as another conversion" because conversions are allowed to overload on // return type but methods are not. // // (*) NOTE: Throughout the rest of this method I will use "field" as a shorthand for // "non-method, non-conversion, non-type member", rather than spelling out // "field, property or event...") foreach (var pair in membersByName) { var name = pair.Key; Symbol? lastSym = GetTypeMembers(name).FirstOrDefault(); methodsBySignature.Clear(); // Conversion collisions do not consider the name of the conversion, // so do not clear that dictionary. foreach (var symbol in pair.Value) { if (symbol.Kind == SymbolKind.NamedType || symbol.IsAccessor() || symbol.IsIndexer()) { continue; } // We detect the first category of conflict by running down the list of members // of the same name, and producing an error when we discover any of the following // "bad transitions". // // * a method or conversion that comes after any field (not necessarily directly) // * a field directly following a field // * a field directly following a method or conversion // // Furthermore: we do not wish to detect collisions between nested types in // this code; that is tested elsewhere. However, we do wish to detect a collision // between a nested type and a field, method or conversion. Therefore we // initialize our "bad transition" detector with a type of the given name, // if there is one. That way we also detect the transitions of "method following // type", and so on. // // The "lastSym" local below is used to detect these transitions. Its value is // one of the following: // // * a nested type of the given name, or // * the first method of the given name, or // * the most recently processed field of the given name. // // If either the current symbol or the "last symbol" are not methods then // there must be a collision: // // * if the current symbol is not a method and the last symbol is, then // there is a field directly following a method of the same name // * if the current symbol is a method and the last symbol is not, then // there is a method directly or indirectly following a field of the same name, // or a method of the same name as a nested type. // * if neither are methods then either we have a field directly // following a field of the same name, or a field and a nested type of the same name. // if (lastSym is object) { if (symbol.Kind != SymbolKind.Method || lastSym.Kind != SymbolKind.Method) { if (symbol.Kind != SymbolKind.Field || !symbol.IsImplicitlyDeclared) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, symbol.Locations[0], this, symbol.Name); } } if (lastSym.Kind == SymbolKind.Method) { lastSym = symbol; } } } else { lastSym = symbol; } // That takes care of the first category of conflict; we detect the // second and third categories as follows: var conversion = symbol as SourceUserDefinedConversionSymbol; var method = symbol as SourceMemberMethodSymbol; if (!(conversion is null)) { // Does this conversion collide *as a conversion* with any previously-seen // conversion? if (!conversionsAsConversions.Add(conversion)) { // CS0557: Duplicate user-defined conversion in type 'C' diagnostics.Add(ErrorCode.ERR_DuplicateConversionInClass, conversion.Locations[0], this); } else { // The other set might already contain a conversion which would collide // *as a method* with the current conversion. if (!conversionsAsMethods.ContainsKey(conversion)) { conversionsAsMethods.Add(conversion, conversion); } } // Does this conversion collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(conversion, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, conversion, previousMethod); } // Do not add the conversion to the set of previously-seen methods; that set // is only non-conversion methods. } else if (!(method is null)) { // Does this method collide *as a method* with any previously-seen // conversion? if (conversionsAsMethods.TryGetValue(method, out var previousConversion)) { ReportMethodSignatureCollision(diagnostics, method, previousConversion); } // Do not add the method to the set of previously-seen conversions. // Does this method collide *as a method* with any previously-seen // non-conversion method? if (methodsBySignature.TryGetValue(method, out var previousMethod)) { ReportMethodSignatureCollision(diagnostics, method, previousMethod); } else { // We haven't seen this method before. Make a note of it in case // we see a colliding method later. methodsBySignature.Add(method, method); } } } } } // Report a name conflict; the error is reported on the location of method1. // UNDONE: Consider adding a secondary location pointing to the second method. private void ReportMethodSignatureCollision(BindingDiagnosticBag diagnostics, SourceMemberMethodSymbol method1, SourceMemberMethodSymbol method2) { switch (method1, method2) { case (SourceOrdinaryMethodSymbol { IsPartialDefinition: true }, SourceOrdinaryMethodSymbol { IsPartialImplementation: true }): case (SourceOrdinaryMethodSymbol { IsPartialImplementation: true }, SourceOrdinaryMethodSymbol { IsPartialDefinition: true }): // these could be 2 parts of the same partial method. // Partial methods are allowed to collide by signature. return; case (SynthesizedSimpleProgramEntryPointSymbol { }, SynthesizedSimpleProgramEntryPointSymbol { }): return; } // If method1 is a constructor only because its return type is missing, then // we've already produced a diagnostic for the missing return type and we suppress the // diagnostic about duplicate signature. if (method1.MethodKind == MethodKind.Constructor && ((ConstructorDeclarationSyntax)method1.SyntaxRef.GetSyntax()).Identifier.ValueText != this.Name) { return; } Debug.Assert(method1.ParameterCount == method2.ParameterCount); for (int i = 0; i < method1.ParameterCount; i++) { var refKind1 = method1.Parameters[i].RefKind; var refKind2 = method2.Parameters[i].RefKind; if (refKind1 != refKind2) { // '{0}' cannot define an overloaded {1} that differs only on parameter modifiers '{2}' and '{3}' var methodKind = method1.MethodKind == MethodKind.Constructor ? MessageID.IDS_SK_CONSTRUCTOR : MessageID.IDS_SK_METHOD; diagnostics.Add(ErrorCode.ERR_OverloadRefKind, method1.Locations[0], this, methodKind.Localize(), refKind1.ToParameterDisplayString(), refKind2.ToParameterDisplayString()); return; } } // Special case: if there are two destructors, use the destructor syntax instead of "Finalize" var methodName = (method1.MethodKind == MethodKind.Destructor && method2.MethodKind == MethodKind.Destructor) ? "~" + this.Name : (method1.IsConstructor() ? this.Name : method1.Name); // Type '{1}' already defines a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, method1.Locations[0], methodName, this); } private void CheckIndexerNameConflicts(BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName) { PooledHashSet<string>? typeParameterNames = null; if (this.Arity > 0) { typeParameterNames = PooledHashSet<string>.GetInstance(); foreach (TypeParameterSymbol typeParameter in this.TypeParameters) { typeParameterNames.Add(typeParameter.Name); } } var indexersBySignature = new Dictionary<PropertySymbol, PropertySymbol>(MemberSignatureComparer.DuplicateSourceComparer); // Note: Can't assume that all indexers are called WellKnownMemberNames.Indexer because // they may be explicit interface implementations. foreach (var members in membersByName.Values) { string? lastIndexerName = null; indexersBySignature.Clear(); foreach (var symbol in members) { if (symbol.IsIndexer()) { PropertySymbol indexer = (PropertySymbol)symbol; CheckIndexerSignatureCollisions( indexer, diagnostics, membersByName, indexersBySignature, ref lastIndexerName); // Also check for collisions with type parameters, which aren't in the member map. // NOTE: Accessors have normal names and are handled in CheckTypeParameterNameConflicts. if (typeParameterNames != null) { string indexerName = indexer.MetadataName; if (typeParameterNames.Contains(indexerName)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); continue; } } } } } typeParameterNames?.Free(); } private void CheckIndexerSignatureCollisions( PropertySymbol indexer, BindingDiagnosticBag diagnostics, Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<PropertySymbol, PropertySymbol> indexersBySignature, ref string? lastIndexerName) { if (!indexer.IsExplicitInterfaceImplementation) //explicit implementation names are not checked { string indexerName = indexer.MetadataName; if (lastIndexerName != null && lastIndexerName != indexerName) { // NOTE: dev10 checks indexer names by comparing each to the previous. // For example, if indexers are declared with names A, B, A, B, then there // will be three errors - one for each time the name is different from the // previous one. If, on the other hand, the names are A, A, B, B, then // there will only be one error because only one indexer has a different // name from the previous one. diagnostics.Add(ErrorCode.ERR_InconsistentIndexerNames, indexer.Locations[0]); } lastIndexerName = indexerName; if (Locations.Length == 1 || IsPartial) { if (membersByName.ContainsKey(indexerName)) { // The name of the indexer is reserved - it can only be used by other indexers. Debug.Assert(!membersByName[indexerName].Any(SymbolExtensions.IsIndexer)); diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, indexer.Locations[0], this, indexerName); } } } if (indexersBySignature.TryGetValue(indexer, out var prevIndexerBySignature)) { // Type '{1}' already defines a member called '{0}' with the same parameter types // NOTE: Dev10 prints "this" as the name of the indexer. diagnostics.Add(ErrorCode.ERR_MemberAlreadyExists, indexer.Locations[0], SyntaxFacts.GetText(SyntaxKind.ThisKeyword), this); } else { indexersBySignature[indexer] = indexer; } } private void CheckSpecialMemberErrors(BindingDiagnosticBag diagnostics) { var conversions = new TypeConversions(this.ContainingAssembly.CorLibrary); foreach (var member in this.GetMembersUnordered()) { member.AfterAddingTypeMembersChecks(conversions, diagnostics); } } private void CheckTypeParameterNameConflicts(BindingDiagnosticBag diagnostics) { if (this.TypeKind == TypeKind.Delegate) { // Delegates do not have conflicts between their type parameter // names and their methods; it is legal (though odd) to say // delegate void D<Invoke>(Invoke x); return; } if (Locations.Length == 1 || IsPartial) { foreach (var tp in TypeParameters) { foreach (var dup in GetMembers(tp.Name)) { diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, dup.Locations[0], this, tp.Name); } } } } private void CheckAccessorNameConflicts(BindingDiagnosticBag diagnostics) { // Report errors where property and event accessors // conflict with other members of the same name. foreach (Symbol symbol in this.GetMembersUnordered()) { if (symbol.IsExplicitInterfaceImplementation()) { // If there's a name conflict it will show up as a more specific // interface implementation error. continue; } switch (symbol.Kind) { case SymbolKind.Property: { var propertySymbol = (PropertySymbol)symbol; this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: true, diagnostics: diagnostics); this.CheckForMemberConflictWithPropertyAccessor(propertySymbol, getNotSet: false, diagnostics: diagnostics); break; } case SymbolKind.Event: { var eventSymbol = (EventSymbol)symbol; this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: true, diagnostics: diagnostics); this.CheckForMemberConflictWithEventAccessor(eventSymbol, isAdder: false, diagnostics: diagnostics); break; } } } } internal override bool KnownCircularStruct { get { if (_lazyKnownCircularStruct == (int)ThreeState.Unknown) { if (TypeKind != TypeKind.Struct) { Interlocked.CompareExchange(ref _lazyKnownCircularStruct, (int)ThreeState.False, (int)ThreeState.Unknown); } else { var diagnostics = BindingDiagnosticBag.GetInstance(); var value = (int)CheckStructCircularity(diagnostics).ToThreeState(); if (Interlocked.CompareExchange(ref _lazyKnownCircularStruct, value, (int)ThreeState.Unknown) == (int)ThreeState.Unknown) { AddDeclarationDiagnostics(diagnostics); } Debug.Assert(value == _lazyKnownCircularStruct); diagnostics.Free(); } } return _lazyKnownCircularStruct == (int)ThreeState.True; } } private bool CheckStructCircularity(BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); CheckFiniteFlatteningGraph(diagnostics); return HasStructCircularity(diagnostics); } private bool HasStructCircularity(BindingDiagnosticBag diagnostics) { foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member.Kind != SymbolKind.Field) { // NOTE: don't have to check field-like events, because they can't have struct types. continue; } var field = (FieldSymbol)member; if (field.IsStatic) { continue; } var type = field.NonPointerType(); if (((object)type != null) && (type.TypeKind == TypeKind.Struct) && BaseTypeAnalysis.StructDependsOn((NamedTypeSymbol)type, this) && !type.IsPrimitiveRecursiveStruct()) // allow System.Int32 to contain a field of its own type { // If this is a backing field, report the error on the associated property. var symbol = field.AssociatedSymbol ?? field; if (symbol.Kind == SymbolKind.Parameter) { // We should stick to members for this error. symbol = field; } // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, symbol.Locations[0], symbol, type); return true; } } } return false; } private void CheckForProtectedInStaticClass(BindingDiagnosticBag diagnostics) { if (!IsStatic) { return; } // no protected members allowed foreach (var valuesByName in GetMembersByName().Values) { foreach (var member in valuesByName) { if (member is TypeSymbol) { // Duplicate Dev10's failure to diagnose this error. continue; } if (member.DeclaredAccessibility.HasProtected()) { if (member.Kind != SymbolKind.Method || ((MethodSymbol)member).MethodKind != MethodKind.Destructor) { diagnostics.Add(ErrorCode.ERR_ProtectedInStatic, member.Locations[0], member); } } } } } private void CheckForUnmatchedOperators(BindingDiagnosticBag diagnostics) { // SPEC: The true and false unary operators require pairwise declaration. // SPEC: A compile-time error occurs if a class or struct declares one // SPEC: of these operators without also declaring the other. // // SPEC DEFICIENCY: The line of the specification quoted above should say // the same thing as the lines below: that the formal parameters of the // paired true/false operators must match exactly. You can't do // op true(S) and op false(S?) for example. // SPEC: Certain binary operators require pairwise declaration. For every // SPEC: declaration of either operator of a pair, there must be a matching // SPEC: declaration of the other operator of the pair. Two operator // SPEC: declarations match when they have the same return type and the same // SPEC: type for each parameter. The following operators require pairwise // SPEC: declaration: == and !=, > and <, >= and <=. CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.TrueOperatorName, WellKnownMemberNames.FalseOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.EqualityOperatorName, WellKnownMemberNames.InequalityOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOperatorName, WellKnownMemberNames.GreaterThanOperatorName); CheckForUnmatchedOperator(diagnostics, WellKnownMemberNames.LessThanOrEqualOperatorName, WellKnownMemberNames.GreaterThanOrEqualOperatorName); // We also produce a warning if == / != is overridden without also overriding // Equals and GetHashCode, or if Equals is overridden without GetHashCode. CheckForEqualityAndGetHashCode(diagnostics); } private void CheckForUnmatchedOperator(BindingDiagnosticBag diagnostics, string operatorName1, string operatorName2) { var ops1 = this.GetOperators(operatorName1); var ops2 = this.GetOperators(operatorName2); CheckForUnmatchedOperator(diagnostics, ops1, ops2, operatorName2); CheckForUnmatchedOperator(diagnostics, ops2, ops1, operatorName1); } private static void CheckForUnmatchedOperator( BindingDiagnosticBag diagnostics, ImmutableArray<MethodSymbol> ops1, ImmutableArray<MethodSymbol> ops2, string operatorName2) { foreach (var op1 in ops1) { bool foundMatch = false; foreach (var op2 in ops2) { foundMatch = DoOperatorsPair(op1, op2); if (foundMatch) { break; } } if (!foundMatch) { // CS0216: The operator 'C.operator true(C)' requires a matching operator 'false' to also be defined diagnostics.Add(ErrorCode.ERR_OperatorNeedsMatch, op1.Locations[0], op1, SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName2))); } } } private static bool DoOperatorsPair(MethodSymbol op1, MethodSymbol op2) { if (op1.ParameterCount != op2.ParameterCount) { return false; } for (int p = 0; p < op1.ParameterCount; ++p) { if (!op1.ParameterTypesWithAnnotations[p].Equals(op2.ParameterTypesWithAnnotations[p], TypeCompareKind.AllIgnoreOptions)) { return false; } } if (!op1.ReturnType.Equals(op2.ReturnType, TypeCompareKind.AllIgnoreOptions)) { return false; } return true; } private void CheckForEqualityAndGetHashCode(BindingDiagnosticBag diagnostics) { if (this.IsInterfaceType()) { // Interfaces are allowed to define Equals without GetHashCode if they want. return; } if (IsRecord || IsRecordStruct) { // For records the warnings reported below are simply going to echo record specific errors, // producing more noise. return; } bool hasOp = this.GetOperators(WellKnownMemberNames.EqualityOperatorName).Any() || this.GetOperators(WellKnownMemberNames.InequalityOperatorName).Any(); bool overridesEquals = this.TypeOverridesObjectMethod("Equals"); if (hasOp || overridesEquals) { bool overridesGHC = this.TypeOverridesObjectMethod("GetHashCode"); if (overridesEquals && !overridesGHC) { // CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualsWithoutGetHashCode, this.Locations[0], this); } if (hasOp && !overridesEquals) { // CS0660: 'C' defines operator == or operator != but does not override Object.Equals(object o) diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutEquals, this.Locations[0], this); } if (hasOp && !overridesGHC) { // CS0661: 'C' defines operator == or operator != but does not override Object.GetHashCode() diagnostics.Add(ErrorCode.WRN_EqualityOpWithoutGetHashCode, this.Locations[0], this); } } } private bool TypeOverridesObjectMethod(string name) { foreach (var method in this.GetMembers(name).OfType<MethodSymbol>()) { if (method.IsOverride && method.GetConstructedLeastOverriddenMethod(this, requireSameReturnType: false).ContainingType.SpecialType == Microsoft.CodeAnalysis.SpecialType.System_Object) { return true; } } return false; } private void CheckFiniteFlatteningGraph(BindingDiagnosticBag diagnostics) { Debug.Assert(ReferenceEquals(this, this.OriginalDefinition)); if (AllTypeArgumentCount() == 0) return; var instanceMap = new Dictionary<NamedTypeSymbol, NamedTypeSymbol>(ReferenceEqualityComparer.Instance); instanceMap.Add(this, this); foreach (var m in this.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(this, type, instanceMap)) { // Struct member '{0}' of type '{1}' causes a cycle in the struct layout diagnostics.Add(ErrorCode.ERR_StructLayoutCycle, f.Locations[0], f, type); //this.KnownCircularStruct = true; return; } } } private static bool InfiniteFlatteningGraph(SourceMemberContainerTypeSymbol top, NamedTypeSymbol t, Dictionary<NamedTypeSymbol, NamedTypeSymbol> instanceMap) { if (!t.ContainsTypeParameter()) return false; var tOriginal = t.OriginalDefinition; if (instanceMap.TryGetValue(tOriginal, out var oldInstance)) { // short circuit when we find a cycle, but only return true when the cycle contains the top struct return (!TypeSymbol.Equals(oldInstance, t, TypeCompareKind.AllNullableIgnoreOptions)) && ReferenceEquals(tOriginal, top); } else { instanceMap.Add(tOriginal, t); try { foreach (var m in t.GetMembersUnordered()) { var f = m as FieldSymbol; if (f is null || !f.IsStatic || f.Type.TypeKind != TypeKind.Struct) continue; var type = (NamedTypeSymbol)f.Type; if (InfiniteFlatteningGraph(top, type, instanceMap)) return true; } return false; } finally { instanceMap.Remove(tOriginal); } } } private void CheckSequentialOnPartialType(BindingDiagnosticBag diagnostics) { if (!IsPartial || this.Layout.Kind != LayoutKind.Sequential) { return; } SyntaxReference? whereFoundField = null; if (this.SyntaxReferences.Length <= 1) { return; } foreach (var syntaxRef in this.SyntaxReferences) { var syntax = syntaxRef.GetSyntax() as TypeDeclarationSyntax; if (syntax == null) { continue; } foreach (var m in syntax.Members) { if (HasInstanceData(m)) { if (whereFoundField != null && whereFoundField != syntaxRef) { diagnostics.Add(ErrorCode.WRN_SequentialOnPartialClass, Locations[0], this); return; } whereFoundField = syntaxRef; } } } } private static bool HasInstanceData(MemberDeclarationSyntax m) { switch (m.Kind()) { case SyntaxKind.FieldDeclaration: var fieldDecl = (FieldDeclarationSyntax)m; return !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(fieldDecl.Modifiers, SyntaxKind.ConstKeyword); case SyntaxKind.PropertyDeclaration: // auto-property var propertyDecl = (PropertyDeclarationSyntax)m; return !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(propertyDecl.Modifiers, SyntaxKind.ExternKeyword) && propertyDecl.AccessorList != null && All(propertyDecl.AccessorList.Accessors, a => a.Body == null && a.ExpressionBody == null); case SyntaxKind.EventFieldDeclaration: // field-like event declaration var eventFieldDecl = (EventFieldDeclarationSyntax)m; return !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.StaticKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.AbstractKeyword) && !ContainsModifier(eventFieldDecl.Modifiers, SyntaxKind.ExternKeyword); default: return false; } } private static bool All<T>(SyntaxList<T> list, Func<T, bool> predicate) where T : CSharpSyntaxNode { foreach (var t in list) { if (predicate(t)) return true; }; return false; } private static bool ContainsModifier(SyntaxTokenList modifiers, SyntaxKind modifier) { foreach (var m in modifiers) { if (m.IsKind(modifier)) return true; }; return false; } private Dictionary<string, ImmutableArray<Symbol>> MakeAllMembers(BindingDiagnosticBag diagnostics) { Dictionary<string, ImmutableArray<Symbol>> membersByName; var membersAndInitializers = GetMembersAndInitializers(); // Most types don't have indexers. If this is one of those types, // just reuse the dictionary we build for early attribute decoding. // For tuples, we also need to take the slow path. if (!membersAndInitializers.HaveIndexers && !this.IsTupleType && _lazyEarlyAttributeDecodingMembersDictionary is object) { membersByName = _lazyEarlyAttributeDecodingMembersDictionary; } else { membersByName = membersAndInitializers.NonTypeMembers.ToDictionary(s => s.Name, StringOrdinalComparer.Instance); // Merge types into the member dictionary AddNestedTypesToDictionary(membersByName, GetTypeMembersDictionary()); } MergePartialMembers(ref membersByName, diagnostics); return membersByName; } private static void AddNestedTypesToDictionary(Dictionary<string, ImmutableArray<Symbol>> membersByName, Dictionary<string, ImmutableArray<NamedTypeSymbol>> typesByName) { foreach (var pair in typesByName) { string name = pair.Key; ImmutableArray<NamedTypeSymbol> types = pair.Value; ImmutableArray<Symbol> typesAsSymbols = StaticCast<Symbol>.From(types); ImmutableArray<Symbol> membersForName; if (membersByName.TryGetValue(name, out membersForName)) { membersByName[name] = membersForName.Concat(typesAsSymbols); } else { membersByName.Add(name, typesAsSymbols); } } } private sealed class DeclaredMembersAndInitializersBuilder { public ArrayBuilder<Symbol> NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> StaticInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public readonly ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> InstanceInitializers = ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>>.GetInstance(); public bool HaveIndexers; public RecordDeclarationSyntax? RecordDeclarationWithParameters; public SynthesizedRecordConstructor? RecordPrimaryConstructor; public bool IsNullableEnabledForInstanceConstructorsAndFields; public bool IsNullableEnabledForStaticConstructorsAndFields; public DeclaredMembersAndInitializers ToReadOnlyAndFree(CSharpCompilation compilation) { return new DeclaredMembersAndInitializers( NonTypeMembers.ToImmutableAndFree(), MembersAndInitializersBuilder.ToReadOnlyAndFree(StaticInitializers), MembersAndInitializersBuilder.ToReadOnlyAndFree(InstanceInitializers), HaveIndexers, RecordDeclarationWithParameters, RecordPrimaryConstructor, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields, compilation); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, bool value) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || value; } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } public void Free() { NonTypeMembers.Free(); foreach (var group in StaticInitializers) { group.Free(); } StaticInitializers.Free(); foreach (var group in InstanceInitializers) { group.Free(); } InstanceInitializers.Free(); } internal void AddOrWrapTupleMembers(SourceMemberContainerTypeSymbol type) { this.NonTypeMembers = type.AddOrWrapTupleMembers(this.NonTypeMembers.ToImmutableAndFree()); } } protected sealed class DeclaredMembersAndInitializers { public readonly ImmutableArray<Symbol> NonTypeMembers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> StaticInitializers; public readonly ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> InstanceInitializers; public readonly bool HaveIndexers; public readonly RecordDeclarationSyntax? RecordDeclarationWithParameters; public readonly SynthesizedRecordConstructor? RecordPrimaryConstructor; public readonly bool IsNullableEnabledForInstanceConstructorsAndFields; public readonly bool IsNullableEnabledForStaticConstructorsAndFields; public static readonly DeclaredMembersAndInitializers UninitializedSentinel = new DeclaredMembersAndInitializers(); private DeclaredMembersAndInitializers() { } public DeclaredMembersAndInitializers( ImmutableArray<Symbol> nonTypeMembers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> staticInitializers, ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> instanceInitializers, bool haveIndexers, RecordDeclarationSyntax? recordDeclarationWithParameters, SynthesizedRecordConstructor? recordPrimaryConstructor, bool isNullableEnabledForInstanceConstructorsAndFields, bool isNullableEnabledForStaticConstructorsAndFields, CSharpCompilation compilation) { Debug.Assert(!nonTypeMembers.IsDefault); AssertInitializers(staticInitializers, compilation); AssertInitializers(instanceInitializers, compilation); Debug.Assert(!nonTypeMembers.Any(s => s is TypeSymbol)); Debug.Assert(recordDeclarationWithParameters is object == recordPrimaryConstructor is object); this.NonTypeMembers = nonTypeMembers; this.StaticInitializers = staticInitializers; this.InstanceInitializers = instanceInitializers; this.HaveIndexers = haveIndexers; this.RecordDeclarationWithParameters = recordDeclarationWithParameters; this.RecordPrimaryConstructor = recordPrimaryConstructor; this.IsNullableEnabledForInstanceConstructorsAndFields = isNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = isNullableEnabledForStaticConstructorsAndFields; } [Conditional("DEBUG")] public static void AssertInitializers(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers, CSharpCompilation compilation) { Debug.Assert(!initializers.IsDefault); if (initializers.IsEmpty) { return; } foreach (ImmutableArray<FieldOrPropertyInitializer> group in initializers) { Debug.Assert(!group.IsDefaultOrEmpty); } for (int i = 0; i < initializers.Length; i++) { if (i > 0) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i - 1].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } if (i + 1 < initializers.Length) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i + 1].Last().Syntax, compilation)) < 0); } if (initializers[i].Length != 1) { Debug.Assert(LexicalSortKey.Compare(new LexicalSortKey(initializers[i].First().Syntax, compilation), new LexicalSortKey(initializers[i].Last().Syntax, compilation)) < 0); } } } } private sealed class MembersAndInitializersBuilder { public ArrayBuilder<Symbol>? NonTypeMembers; private ArrayBuilder<FieldOrPropertyInitializer>? InstanceInitializersForPositionalMembers; private bool IsNullableEnabledForInstanceConstructorsAndFields; private bool IsNullableEnabledForStaticConstructorsAndFields; public MembersAndInitializersBuilder(DeclaredMembersAndInitializers declaredMembersAndInitializers) { Debug.Assert(declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel); this.IsNullableEnabledForInstanceConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; this.IsNullableEnabledForStaticConstructorsAndFields = declaredMembersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields; } public MembersAndInitializers ToReadOnlyAndFree(DeclaredMembersAndInitializers declaredMembers) { var nonTypeMembers = NonTypeMembers?.ToImmutableAndFree() ?? declaredMembers.NonTypeMembers; var instanceInitializers = InstanceInitializersForPositionalMembers is null ? declaredMembers.InstanceInitializers : mergeInitializers(); return new MembersAndInitializers( nonTypeMembers, declaredMembers.StaticInitializers, instanceInitializers, declaredMembers.HaveIndexers, isNullableEnabledForInstanceConstructorsAndFields: IsNullableEnabledForInstanceConstructorsAndFields, isNullableEnabledForStaticConstructorsAndFields: IsNullableEnabledForStaticConstructorsAndFields); ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> mergeInitializers() { Debug.Assert(InstanceInitializersForPositionalMembers.Count != 0); Debug.Assert(declaredMembers.RecordPrimaryConstructor is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters is object); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.SyntaxTree == InstanceInitializersForPositionalMembers[0].Syntax.SyntaxTree); Debug.Assert(declaredMembers.RecordDeclarationWithParameters.Span.Contains(InstanceInitializersForPositionalMembers[0].Syntax.Span.Start)); var groupCount = declaredMembers.InstanceInitializers.Length; if (groupCount == 0) { return ImmutableArray.Create(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); } var compilation = declaredMembers.RecordPrimaryConstructor.DeclaringCompilation; var sortKey = new LexicalSortKey(InstanceInitializersForPositionalMembers.First().Syntax, compilation); int insertAt; for (insertAt = 0; insertAt < groupCount; insertAt++) { if (LexicalSortKey.Compare(sortKey, new LexicalSortKey(declaredMembers.InstanceInitializers[insertAt][0].Syntax, compilation)) < 0) { break; } } ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>> groupsBuilder; if (insertAt != groupCount && declaredMembers.RecordDeclarationWithParameters.SyntaxTree == declaredMembers.InstanceInitializers[insertAt][0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(declaredMembers.InstanceInitializers[insertAt][0].Syntax.Span.Start)) { // Need to merge into the previous group var declaredInitializers = declaredMembers.InstanceInitializers[insertAt]; var insertedInitializers = InstanceInitializersForPositionalMembers; #if DEBUG // initializers should be added in syntax order: Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.SyntaxTree == declaredInitializers[0].Syntax.SyntaxTree); Debug.Assert(insertedInitializers[insertedInitializers.Count - 1].Syntax.Span.Start < declaredInitializers[0].Syntax.Span.Start); #endif insertedInitializers.AddRange(declaredInitializers); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(insertedInitializers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt + 1, groupCount - (insertAt + 1)); Debug.Assert(groupsBuilder.Count == groupCount); } else { Debug.Assert(!declaredMembers.InstanceInitializers.Any(g => declaredMembers.RecordDeclarationWithParameters.SyntaxTree == g[0].Syntax.SyntaxTree && declaredMembers.RecordDeclarationWithParameters.Span.Contains(g[0].Syntax.Span.Start))); groupsBuilder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(groupCount + 1); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt); groupsBuilder.Add(InstanceInitializersForPositionalMembers.ToImmutableAndFree()); groupsBuilder.AddRange(declaredMembers.InstanceInitializers, insertAt, groupCount - insertAt); Debug.Assert(groupsBuilder.Count == groupCount + 1); } var result = groupsBuilder.ToImmutableAndFree(); DeclaredMembersAndInitializers.AssertInitializers(result, compilation); return result; } } public void AddInstanceInitializerForPositionalMembers(FieldOrPropertyInitializer initializer) { if (InstanceInitializersForPositionalMembers is null) { InstanceInitializersForPositionalMembers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } InstanceInitializersForPositionalMembers.Add(initializer); } public IReadOnlyCollection<Symbol> GetNonTypeMembers(DeclaredMembersAndInitializers declaredMembers) { return NonTypeMembers ?? (IReadOnlyCollection<Symbol>)declaredMembers.NonTypeMembers; } public void AddNonTypeMember(Symbol member, DeclaredMembersAndInitializers declaredMembers) { if (NonTypeMembers is null) { NonTypeMembers = ArrayBuilder<Symbol>.GetInstance(declaredMembers.NonTypeMembers.Length + 1); NonTypeMembers.AddRange(declaredMembers.NonTypeMembers); } NonTypeMembers.Add(member); } public void UpdateIsNullableEnabledForConstructorsAndFields(bool useStatic, CSharpCompilation compilation, CSharpSyntaxNode syntax) { ref bool isNullableEnabled = ref GetIsNullableEnabledForConstructorsAndFields(useStatic); isNullableEnabled = isNullableEnabled || compilation.IsNullableAnalysisEnabledIn(syntax); } private ref bool GetIsNullableEnabledForConstructorsAndFields(bool useStatic) { return ref useStatic ? ref IsNullableEnabledForStaticConstructorsAndFields : ref IsNullableEnabledForInstanceConstructorsAndFields; } internal static ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> ToReadOnlyAndFree(ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> initializers) { if (initializers.Count == 0) { initializers.Free(); return ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>>.Empty; } var builder = ArrayBuilder<ImmutableArray<FieldOrPropertyInitializer>>.GetInstance(initializers.Count); foreach (ArrayBuilder<FieldOrPropertyInitializer> group in initializers) { builder.Add(group.ToImmutableAndFree()); } initializers.Free(); return builder.ToImmutableAndFree(); } public void Free() { NonTypeMembers?.Free(); InstanceInitializersForPositionalMembers?.Free(); } } private MembersAndInitializers? BuildMembersAndInitializers(BindingDiagnosticBag diagnostics) { var declaredMembersAndInitializers = getDeclaredMembersAndInitializers(); if (declaredMembersAndInitializers is null) { // Another thread completed the work before this one return null; } var membersAndInitializersBuilder = new MembersAndInitializersBuilder(declaredMembersAndInitializers); AddSynthesizedMembers(membersAndInitializersBuilder, declaredMembersAndInitializers, diagnostics); if (Volatile.Read(ref _lazyMembersAndInitializers) != null) { // Another thread completed the work before this one membersAndInitializersBuilder.Free(); return null; } return membersAndInitializersBuilder.ToReadOnlyAndFree(declaredMembersAndInitializers); DeclaredMembersAndInitializers? getDeclaredMembersAndInitializers() { var declaredMembersAndInitializers = _lazyDeclaredMembersAndInitializers; if (declaredMembersAndInitializers != DeclaredMembersAndInitializers.UninitializedSentinel) { return declaredMembersAndInitializers; } if (Volatile.Read(ref _lazyMembersAndInitializers) is not null) { // We're previously computed declared members and already cleared them out // No need to compute them again return null; } var diagnostics = BindingDiagnosticBag.GetInstance(); declaredMembersAndInitializers = buildDeclaredMembersAndInitializers(diagnostics); var alreadyKnown = Interlocked.CompareExchange(ref _lazyDeclaredMembersAndInitializers, declaredMembersAndInitializers, DeclaredMembersAndInitializers.UninitializedSentinel); if (alreadyKnown != DeclaredMembersAndInitializers.UninitializedSentinel) { diagnostics.Free(); return alreadyKnown; } AddDeclarationDiagnostics(diagnostics); diagnostics.Free(); return declaredMembersAndInitializers!; } // Builds explicitly declared members (as opposed to synthesized members). // This should not attempt to bind any method parameters as that would cause // the members being built to be captured in the binder cache before the final // list of members is determined. DeclaredMembersAndInitializers? buildDeclaredMembersAndInitializers(BindingDiagnosticBag diagnostics) { var builder = new DeclaredMembersAndInitializersBuilder(); AddDeclaredNontypeMembers(builder, diagnostics); switch (TypeKind) { case TypeKind.Struct: CheckForStructBadInitializers(builder, diagnostics); CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: false, diagnostics: diagnostics); break; case TypeKind.Enum: CheckForStructDefaultConstructors(builder.NonTypeMembers, isEnum: true, diagnostics: diagnostics); break; case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: // No additional checking required. break; default: break; } if (IsTupleType) { builder.AddOrWrapTupleMembers(this); } if (Volatile.Read(ref _lazyDeclaredMembersAndInitializers) != DeclaredMembersAndInitializers.UninitializedSentinel) { // _lazyDeclaredMembersAndInitializers is already computed. no point to continue. builder.Free(); return null; } return builder.ToReadOnlyAndFree(DeclaringCompilation); } } internal ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> GetSimpleProgramEntryPoints() { if (_lazySimpleProgramEntryPoints.IsDefault) { var diagnostics = BindingDiagnosticBag.GetInstance(); var simpleProgramEntryPoints = buildSimpleProgramEntryPoint(diagnostics); if (ImmutableInterlocked.InterlockedInitialize(ref _lazySimpleProgramEntryPoints, simpleProgramEntryPoints)) { AddDeclarationDiagnostics(diagnostics); } diagnostics.Free(); } Debug.Assert(!_lazySimpleProgramEntryPoints.IsDefault); return _lazySimpleProgramEntryPoints; ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol> buildSimpleProgramEntryPoint(BindingDiagnosticBag diagnostics) { if (this.ContainingSymbol is not NamespaceSymbol { IsGlobalNamespace: true } || this.Name != WellKnownMemberNames.TopLevelStatementsEntryPointTypeName) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>? builder = null; foreach (var singleDecl in declaration.Declarations) { if (singleDecl.IsSimpleProgram) { if (builder is null) { builder = ArrayBuilder<SynthesizedSimpleProgramEntryPointSymbol>.GetInstance(); } else { Binder.Error(diagnostics, ErrorCode.ERR_SimpleProgramMultipleUnitsWithTopLevelStatements, singleDecl.NameLocation); } builder.Add(new SynthesizedSimpleProgramEntryPointSymbol(this, singleDecl, diagnostics)); } } if (builder is null) { return ImmutableArray<SynthesizedSimpleProgramEntryPointSymbol>.Empty; } return builder.ToImmutableAndFree(); } } private void AddSynthesizedMembers(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (TypeKind is TypeKind.Class) { AddSynthesizedSimpleProgramEntryPointIfNecessary(builder, declaredMembersAndInitializers); } switch (TypeKind) { case TypeKind.Struct: case TypeKind.Enum: case TypeKind.Class: case TypeKind.Interface: case TypeKind.Submission: AddSynthesizedRecordMembersIfNecessary(builder, declaredMembersAndInitializers, diagnostics); AddSynthesizedConstructorsIfNecessary(builder, declaredMembersAndInitializers, diagnostics); break; default: break; } } private void AddDeclaredNontypeMembers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { foreach (var decl in this.declaration.Declarations) { if (!decl.HasAnyNontypeMembers) { continue; } if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } var syntax = decl.SyntaxReference.GetSyntax(); switch (syntax.Kind()) { case SyntaxKind.EnumDeclaration: AddEnumMembers(builder, (EnumDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.DelegateDeclaration: SourceDelegateMethodSymbol.AddDelegateMembers(this, builder.NonTypeMembers, (DelegateDeclarationSyntax)syntax, diagnostics); break; case SyntaxKind.NamespaceDeclaration: case SyntaxKind.FileScopedNamespaceDeclaration: // The members of a global anonymous type is in a syntax tree of a namespace declaration or a compilation unit. AddNonTypeMembers(builder, ((BaseNamespaceDeclarationSyntax)syntax).Members, diagnostics); break; case SyntaxKind.CompilationUnit: AddNonTypeMembers(builder, ((CompilationUnitSyntax)syntax).Members, diagnostics); break; case SyntaxKind.ClassDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.StructDeclaration: var typeDecl = (TypeDeclarationSyntax)syntax; AddNonTypeMembers(builder, typeDecl.Members, diagnostics); break; case SyntaxKind.RecordDeclaration: case SyntaxKind.RecordStructDeclaration: var recordDecl = (RecordDeclarationSyntax)syntax; var parameterList = recordDecl.ParameterList; noteRecordParameters(recordDecl, parameterList, builder, diagnostics); AddNonTypeMembers(builder, recordDecl.Members, diagnostics); break; default: throw ExceptionUtilities.UnexpectedValue(syntax.Kind()); } } void noteRecordParameters(RecordDeclarationSyntax syntax, ParameterListSyntax? parameterList, DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { if (parameterList is null) { return; } if (builder.RecordDeclarationWithParameters is null) { builder.RecordDeclarationWithParameters = syntax; var ctor = new SynthesizedRecordConstructor(this, syntax); builder.RecordPrimaryConstructor = ctor; var compilation = DeclaringCompilation; builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, parameterList); if (syntax is { PrimaryConstructorBaseTypeIfClass: { ArgumentList: { } baseParamList } }) { builder.UpdateIsNullableEnabledForConstructorsAndFields(ctor.IsStatic, compilation, baseParamList); } } else { diagnostics.Add(ErrorCode.ERR_MultipleRecordParameterLists, parameterList.Location); } } } internal Binder GetBinder(CSharpSyntaxNode syntaxNode) { return this.DeclaringCompilation.GetBinder(syntaxNode); } private void MergePartialMembers( ref Dictionary<string, ImmutableArray<Symbol>> membersByName, BindingDiagnosticBag diagnostics) { var memberNames = ArrayBuilder<string>.GetInstance(membersByName.Count); memberNames.AddRange(membersByName.Keys); //key and value will be the same object var methodsBySignature = new Dictionary<MethodSymbol, SourceMemberMethodSymbol>(MemberSignatureComparer.PartialMethodsComparer); foreach (var name in memberNames) { methodsBySignature.Clear(); foreach (var symbol in membersByName[name]) { var method = symbol as SourceMemberMethodSymbol; if (method is null || !method.IsPartial) { continue; // only partial methods need to be merged } if (methodsBySignature.TryGetValue(method, out var prev)) { var prevPart = (SourceOrdinaryMethodSymbol)prev; var methodPart = (SourceOrdinaryMethodSymbol)method; if (methodPart.IsPartialImplementation && (prevPart.IsPartialImplementation || (prevPart.OtherPartOfPartial is MethodSymbol otherImplementation && (object)otherImplementation != methodPart))) { // A partial method may not have multiple implementing declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneActual, methodPart.Locations[0]); } else if (methodPart.IsPartialDefinition && (prevPart.IsPartialDefinition || (prevPart.OtherPartOfPartial is MethodSymbol otherDefinition && (object)otherDefinition != methodPart))) { // A partial method may not have multiple defining declarations diagnostics.Add(ErrorCode.ERR_PartialMethodOnlyOneLatent, methodPart.Locations[0]); } else { if ((object)membersByName == _lazyEarlyAttributeDecodingMembersDictionary) { // Avoid mutating the cached dictionary and especially avoid doing this possibly on multiple threads in parallel. membersByName = new Dictionary<string, ImmutableArray<Symbol>>(membersByName); } membersByName[name] = FixPartialMember(membersByName[name], prevPart, methodPart); } } else { methodsBySignature.Add(method, method); } } foreach (SourceOrdinaryMethodSymbol method in methodsBySignature.Values) { // partial implementations not paired with a definition if (method.IsPartialImplementation && method.OtherPartOfPartial is null) { diagnostics.Add(ErrorCode.ERR_PartialMethodMustHaveLatent, method.Locations[0], method); } else if (method is { IsPartialDefinition: true, OtherPartOfPartial: null, HasExplicitAccessModifier: true }) { diagnostics.Add(ErrorCode.ERR_PartialMethodWithAccessibilityModsMustHaveImplementation, method.Locations[0], method); } } } memberNames.Free(); } /// <summary> /// Fix up a partial method by combining its defining and implementing declarations, updating the array of symbols (by name), /// and returning the combined symbol. /// </summary> /// <param name="symbols">The symbols array containing both the latent and implementing declaration</param> /// <param name="part1">One of the two declarations</param> /// <param name="part2">The other declaration</param> /// <returns>An updated symbols array containing only one method symbol representing the two parts</returns> private static ImmutableArray<Symbol> FixPartialMember(ImmutableArray<Symbol> symbols, SourceOrdinaryMethodSymbol part1, SourceOrdinaryMethodSymbol part2) { SourceOrdinaryMethodSymbol definition; SourceOrdinaryMethodSymbol implementation; if (part1.IsPartialDefinition) { definition = part1; implementation = part2; } else { definition = part2; implementation = part1; } SourceOrdinaryMethodSymbol.InitializePartialMethodParts(definition, implementation); // a partial method is represented in the member list by its definition part: return Remove(symbols, implementation); } private static ImmutableArray<Symbol> Remove(ImmutableArray<Symbol> symbols, Symbol symbol) { var builder = ArrayBuilder<Symbol>.GetInstance(); foreach (var s in symbols) { if (!ReferenceEquals(s, symbol)) { builder.Add(s); } } return builder.ToImmutableAndFree(); } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the property accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithPropertyAccessor( PropertySymbol propertySymbol, bool getNotSet, BindingDiagnosticBag diagnostics) { Debug.Assert(!propertySymbol.IsExplicitInterfaceImplementation); // checked by caller MethodSymbol accessor = getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod; string accessorName; if ((object)accessor != null) { accessorName = accessor.Name; } else { string propertyName = propertySymbol.IsIndexer ? propertySymbol.MetadataName : propertySymbol.Name; accessorName = SourcePropertyAccessorSymbol.GetAccessorName(propertyName, getNotSet, propertySymbol.IsCompilationOutputWinMdObj()); } foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchPropertyAccessor(propertySymbol, getNotSet, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrPropertyLocation(propertySymbol, getNotSet), accessorName, this); return; } } } } /// <summary> /// Report an error if a member (other than a method) exists with the same name /// as the event accessor, or if a method exists with the same name and signature. /// </summary> private void CheckForMemberConflictWithEventAccessor( EventSymbol eventSymbol, bool isAdder, BindingDiagnosticBag diagnostics) { Debug.Assert(!eventSymbol.IsExplicitInterfaceImplementation); // checked by caller string accessorName = SourceEventSymbol.GetAccessorName(eventSymbol.Name, isAdder); foreach (var symbol in GetMembers(accessorName)) { if (symbol.Kind != SymbolKind.Method) { // The type '{0}' already contains a definition for '{1}' if (Locations.Length == 1 || IsPartial) diagnostics.Add(ErrorCode.ERR_DuplicateNameInClass, GetAccessorOrEventLocation(eventSymbol, isAdder), this, accessorName); return; } else { var methodSymbol = (MethodSymbol)symbol; if ((methodSymbol.MethodKind == MethodKind.Ordinary) && ParametersMatchEventAccessor(eventSymbol, methodSymbol.Parameters)) { // Type '{1}' already reserves a member called '{0}' with the same parameter types diagnostics.Add(ErrorCode.ERR_MemberReserved, GetAccessorOrEventLocation(eventSymbol, isAdder), accessorName, this); return; } } } } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the property. /// </summary> private static Location GetAccessorOrPropertyLocation(PropertySymbol propertySymbol, bool getNotSet) { var locationFrom = (Symbol)(getNotSet ? propertySymbol.GetMethod : propertySymbol.SetMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return the location of the accessor, or if no accessor, the location of the event. /// </summary> private static Location GetAccessorOrEventLocation(EventSymbol propertySymbol, bool isAdder) { var locationFrom = (Symbol?)(isAdder ? propertySymbol.AddMethod : propertySymbol.RemoveMethod) ?? propertySymbol; return locationFrom.Locations[0]; } /// <summary> /// Return true if the method parameters match the parameters of the /// property accessor, including the value parameter for the setter. /// </summary> private static bool ParametersMatchPropertyAccessor(PropertySymbol propertySymbol, bool getNotSet, ImmutableArray<ParameterSymbol> methodParams) { var propertyParams = propertySymbol.Parameters; var numParams = propertyParams.Length + (getNotSet ? 0 : 1); if (numParams != methodParams.Length) { return false; } for (int i = 0; i < numParams; i++) { var methodParam = methodParams[i]; if (methodParam.RefKind != RefKind.None) { return false; } var propertyParamType = (((i == numParams - 1) && !getNotSet) ? propertySymbol.TypeWithAnnotations : propertyParams[i].TypeWithAnnotations).Type; if (!propertyParamType.Equals(methodParam.Type, TypeCompareKind.AllIgnoreOptions)) { return false; } } return true; } /// <summary> /// Return true if the method parameters match the parameters of the /// event accessor, including the value parameter. /// </summary> private static bool ParametersMatchEventAccessor(EventSymbol eventSymbol, ImmutableArray<ParameterSymbol> methodParams) { return methodParams.Length == 1 && methodParams[0].RefKind == RefKind.None && eventSymbol.Type.Equals(methodParams[0].Type, TypeCompareKind.AllIgnoreOptions); } private void AddEnumMembers(DeclaredMembersAndInitializersBuilder result, EnumDeclarationSyntax syntax, BindingDiagnosticBag diagnostics) { // The previous enum constant used to calculate subsequent // implicit enum constants. (This is the most recent explicit // enum constant or the first implicit constant if no explicit values.) SourceEnumConstantSymbol? otherSymbol = null; // Offset from "otherSymbol". int otherSymbolOffset = 0; foreach (var member in syntax.Members) { SourceEnumConstantSymbol symbol; var valueOpt = member.EqualsValue; if (valueOpt != null) { symbol = SourceEnumConstantSymbol.CreateExplicitValuedConstant(this, member, diagnostics); } else { symbol = SourceEnumConstantSymbol.CreateImplicitValuedConstant(this, member, otherSymbol, otherSymbolOffset, diagnostics); } result.NonTypeMembers.Add(symbol); if (valueOpt != null || otherSymbol is null) { otherSymbol = symbol; otherSymbolOffset = 1; } else { otherSymbolOffset++; } } } private static void AddInitializer(ref ArrayBuilder<FieldOrPropertyInitializer>? initializers, FieldSymbol? fieldOpt, CSharpSyntaxNode node) { if (initializers == null) { initializers = ArrayBuilder<FieldOrPropertyInitializer>.GetInstance(); } else if (initializers.Count != 0) { // initializers should be added in syntax order: Debug.Assert(node.SyntaxTree == initializers.Last().Syntax.SyntaxTree); Debug.Assert(node.SpanStart > initializers.Last().Syntax.Span.Start); } initializers.Add(new FieldOrPropertyInitializer(fieldOpt, node)); } private static void AddInitializers( ArrayBuilder<ArrayBuilder<FieldOrPropertyInitializer>> allInitializers, ArrayBuilder<FieldOrPropertyInitializer>? siblingsOpt) { if (siblingsOpt != null) { allInitializers.Add(siblingsOpt); } } private static void CheckInterfaceMembers(ImmutableArray<Symbol> nonTypeMembers, BindingDiagnosticBag diagnostics) { foreach (var member in nonTypeMembers) { CheckInterfaceMember(member, diagnostics); } } private static void CheckInterfaceMember(Symbol member, BindingDiagnosticBag diagnostics) { switch (member.Kind) { case SymbolKind.Field: break; case SymbolKind.Method: var meth = (MethodSymbol)member; switch (meth.MethodKind) { case MethodKind.Constructor: diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConstructors, member.Locations[0]); break; case MethodKind.Conversion: if (!meth.IsAbstract) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.UserDefinedOperator: if (!meth.IsAbstract && (meth.Name == WellKnownMemberNames.EqualityOperatorName || meth.Name == WellKnownMemberNames.InequalityOperatorName)) { diagnostics.Add(ErrorCode.ERR_InterfacesCantContainConversionOrEqualityOperators, member.Locations[0]); } break; case MethodKind.Destructor: diagnostics.Add(ErrorCode.ERR_OnlyClassesCanContainDestructors, member.Locations[0]); break; case MethodKind.ExplicitInterfaceImplementation: //CS0541 is handled in SourcePropertySymbol case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.PropertyGet: case MethodKind.PropertySet: case MethodKind.EventAdd: case MethodKind.EventRemove: case MethodKind.StaticConstructor: break; default: throw ExceptionUtilities.UnexpectedValue(meth.MethodKind); } break; case SymbolKind.Property: break; case SymbolKind.Event: break; default: throw ExceptionUtilities.UnexpectedValue(member.Kind); } } private static void CheckForStructDefaultConstructors( ArrayBuilder<Symbol> members, bool isEnum, BindingDiagnosticBag diagnostics) { foreach (var s in members) { var m = s as MethodSymbol; if (!(m is null)) { if (m.MethodKind == MethodKind.Constructor && m.ParameterCount == 0) { var location = m.Locations[0]; if (isEnum) { diagnostics.Add(ErrorCode.ERR_EnumsCantContainDefaultConstructor, location); } else { MessageID.IDS_FeatureParameterlessStructConstructors.CheckFeatureAvailability(diagnostics, m.DeclaringCompilation, location); if (m.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicParameterlessStructConstructor, location); } } } } } } private void CheckForStructBadInitializers(DeclaredMembersAndInitializersBuilder builder, BindingDiagnosticBag diagnostics) { Debug.Assert(TypeKind == TypeKind.Struct); if (builder.RecordDeclarationWithParameters is not null) { Debug.Assert(builder.RecordDeclarationWithParameters is RecordDeclarationSyntax { ParameterList: not null } record && record.Kind() == SyntaxKind.RecordStructDeclaration); return; } foreach (var initializers in builder.InstanceInitializers) { foreach (FieldOrPropertyInitializer initializer in initializers) { var symbol = initializer.FieldOpt.AssociatedSymbol ?? initializer.FieldOpt; MessageID.IDS_FeatureStructFieldInitializers.CheckFeatureAvailability(diagnostics, symbol.DeclaringCompilation, symbol.Locations[0]); } } } private void AddSynthesizedSimpleProgramEntryPointIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers) { var simpleProgramEntryPoints = GetSimpleProgramEntryPoints(); foreach (var member in simpleProgramEntryPoints) { builder.AddNonTypeMember(member, declaredMembersAndInitializers); } } private void AddSynthesizedRecordMembersIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { if (declaration.Kind is not (DeclarationKind.Record or DeclarationKind.RecordStruct)) { return; } ParameterListSyntax? paramList = declaredMembersAndInitializers.RecordDeclarationWithParameters?.ParameterList; var memberSignatures = s_duplicateRecordMemberSignatureDictionary.Allocate(); var fieldsByName = PooledDictionary<string, Symbol>.GetInstance(); var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); var members = ArrayBuilder<Symbol>.GetInstance(membersSoFar.Count + 1); var memberNames = PooledHashSet<string>.GetInstance(); foreach (var member in membersSoFar) { memberNames.Add(member.Name); switch (member) { case EventSymbol: case MethodSymbol { MethodKind: not (MethodKind.Ordinary or MethodKind.Constructor) }: continue; case FieldSymbol { Name: var fieldName }: if (!fieldsByName.ContainsKey(fieldName)) { fieldsByName.Add(fieldName, member); } continue; } if (!memberSignatures.ContainsKey(member)) { memberSignatures.Add(member, member); } } CSharpCompilation compilation = this.DeclaringCompilation; bool isRecordClass = declaration.Kind == DeclarationKind.Record; // Positional record bool primaryAndCopyCtorAmbiguity = false; if (!(paramList is null)) { Debug.Assert(declaredMembersAndInitializers.RecordDeclarationWithParameters is object); // primary ctor var ctor = declaredMembersAndInitializers.RecordPrimaryConstructor; Debug.Assert(ctor is object); members.Add(ctor); if (ctor.ParameterCount != 0) { // properties and Deconstruct var existingOrAddedMembers = addProperties(ctor.Parameters); addDeconstruct(ctor, existingOrAddedMembers); } if (isRecordClass) { primaryAndCopyCtorAmbiguity = ctor.ParameterCount == 1 && ctor.Parameters[0].Type.Equals(this, TypeCompareKind.AllIgnoreOptions); } } if (isRecordClass) { addCopyCtor(primaryAndCopyCtorAmbiguity); addCloneMethod(); } PropertySymbol? equalityContract = isRecordClass ? addEqualityContract() : null; var thisEquals = addThisEquals(equalityContract); if (isRecordClass) { addBaseEquals(); } addObjectEquals(thisEquals); var getHashCode = addGetHashCode(equalityContract); addEqualityOperators(); if (thisEquals is not SynthesizedRecordEquals && getHashCode is SynthesizedRecordGetHashCode) { diagnostics.Add(ErrorCode.WRN_RecordEqualsWithoutGetHashCode, thisEquals.Locations[0], declaration.Name); } var printMembers = addPrintMembersMethod(membersSoFar); addToStringMethod(printMembers); memberSignatures.Free(); fieldsByName.Free(); memberNames.Free(); // Synthesizing non-readonly properties in struct would require changing readonly logic for PrintMembers method synthesis Debug.Assert(isRecordClass || !members.Any(m => m is PropertySymbol { GetMethod.IsEffectivelyReadOnly: false })); // We put synthesized record members first so that errors about conflicts show up on user-defined members rather than all // going to the record declaration members.AddRange(membersSoFar); builder.NonTypeMembers?.Free(); builder.NonTypeMembers = members; return; void addDeconstruct(SynthesizedRecordConstructor ctor, ImmutableArray<Symbol> positionalMembers) { Debug.Assert(positionalMembers.All(p => p is PropertySymbol or FieldSymbol)); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.DeconstructMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ctor.Parameters.SelectAsArray<ParameterSymbol, ParameterSymbol>(param => new SignatureOnlyParameterSymbol(param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.Out )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingDeconstructMethod)) { members.Add(new SynthesizedRecordDeconstruct(this, ctor, positionalMembers, memberOffset: members.Count, diagnostics)); } else { var deconstruct = (MethodSymbol)existingDeconstructMethod; if (deconstruct.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, deconstruct.Locations[0], deconstruct); } if (deconstruct.ReturnType.SpecialType != SpecialType.System_Void && !deconstruct.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, deconstruct.Locations[0], deconstruct, targetMethod.ReturnType); } if (deconstruct.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, deconstruct.Locations[0], deconstruct); } } } void addCopyCtor(bool primaryAndCopyCtorAmbiguity) { Debug.Assert(isRecordClass); var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.InstanceConstructorName, this, MethodKind.Constructor, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Void)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingConstructor)) { var copyCtor = new SynthesizedRecordCopyCtor(this, memberOffset: members.Count); members.Add(copyCtor); if (primaryAndCopyCtorAmbiguity) { diagnostics.Add(ErrorCode.ERR_RecordAmbigCtor, copyCtor.Locations[0]); } } else { var constructor = (MethodSymbol)existingConstructor; if (!this.IsSealed && (constructor.DeclaredAccessibility != Accessibility.Public && constructor.DeclaredAccessibility != Accessibility.Protected)) { diagnostics.Add(ErrorCode.ERR_CopyConstructorWrongAccessibility, constructor.Locations[0], constructor); } } } void addCloneMethod() { Debug.Assert(isRecordClass); members.Add(new SynthesizedRecordClone(this, memberOffset: members.Count, diagnostics)); } MethodSymbol addPrintMembersMethod(IEnumerable<Symbol> userDefinedMembers) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.PrintMembersMethodName, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Text_StringBuilder)), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None)), RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); MethodSymbol printMembersMethod; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingPrintMembersMethod)) { printMembersMethod = new SynthesizedRecordPrintMembers(this, userDefinedMembers, memberOffset: members.Count, diagnostics); members.Add(printMembersMethod); } else { printMembersMethod = (MethodSymbol)existingPrintMembersMethod; if (!isRecordClass || (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType())) { if (printMembersMethod.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } } else if (printMembersMethod.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, printMembersMethod.Locations[0], printMembersMethod); } if (!printMembersMethod.ReturnType.Equals(targetMethod.ReturnType, TypeCompareKind.AllIgnoreOptions)) { if (!printMembersMethod.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, printMembersMethod.Locations[0], printMembersMethod, targetMethod.ReturnType); } } else if (isRecordClass) { SynthesizedRecordPrintMembers.VerifyOverridesPrintMembersFromBase(printMembersMethod, diagnostics); } reportStaticOrNotOverridableAPIInRecord(printMembersMethod, diagnostics); } return printMembersMethod; } void addToStringMethod(MethodSymbol printMethod) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectToString, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, returnType: TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_String)), refCustomModifiers: ImmutableArray<CustomModifier>.Empty, explicitInterfaceImplementations: ImmutableArray<MethodSymbol>.Empty); var baseToStringMethod = getBaseToStringMethod(); if (baseToStringMethod is { IsSealed: true }) { if (baseToStringMethod.ContainingModule != this.ContainingModule && !this.DeclaringCompilation.IsFeatureEnabled(MessageID.IDS_FeatureSealedToStringInRecord)) { var languageVersion = ((CSharpParseOptions)this.Locations[0].SourceTree!.Options).LanguageVersion; var requiredVersion = MessageID.IDS_FeatureSealedToStringInRecord.RequiredVersion(); diagnostics.Add( ErrorCode.ERR_InheritingFromRecordWithSealedToString, this.Locations[0], languageVersion.ToDisplayString(), new CSharpRequiredLanguageVersion(requiredVersion)); } } else { if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingToStringMethod)) { var toStringMethod = new SynthesizedRecordToString( this, printMethod, memberOffset: members.Count, isReadOnly: printMethod.IsEffectivelyReadOnly, diagnostics); members.Add(toStringMethod); } else { var toStringMethod = (MethodSymbol)existingToStringMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(toStringMethod, SpecialMember.System_Object__ToString, diagnostics) && toStringMethod.IsSealed && !IsSealed) { MessageID.IDS_FeatureSealedToStringInRecord.CheckFeatureAvailability( diagnostics, this.DeclaringCompilation, toStringMethod.Locations[0]); } } } MethodSymbol? getBaseToStringMethod() { var objectToString = this.DeclaringCompilation.GetSpecialTypeMember(SpecialMember.System_Object__ToString); var currentBaseType = this.BaseTypeNoUseSiteDiagnostics; while (currentBaseType is not null) { foreach (var member in currentBaseType.GetSimpleNonTypeMembers(WellKnownMemberNames.ObjectToString)) { if (member is not MethodSymbol method) continue; if (method.GetLeastOverriddenMethod(null) == objectToString) return method; } currentBaseType = currentBaseType.BaseTypeNoUseSiteDiagnostics; } return null; } } ImmutableArray<Symbol> addProperties(ImmutableArray<ParameterSymbol> recordParameters) { var existingOrAddedMembers = ArrayBuilder<Symbol>.GetInstance(recordParameters.Length); int addedCount = 0; foreach (ParameterSymbol param in recordParameters) { bool isInherited = false; var syntax = param.GetNonNullSyntaxNode(); var targetProperty = new SignatureOnlyPropertySymbol(param.Name, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, param.TypeWithAnnotations, ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); if (!memberSignatures.TryGetValue(targetProperty, out var existingMember) && !fieldsByName.TryGetValue(param.Name, out existingMember)) { existingMember = OverriddenOrHiddenMembersHelpers.FindFirstHiddenMemberIfAny(targetProperty, memberIsFromSomeCompilation: true); isInherited = true; } // There should be an error if we picked a member that is hidden // This will be fixed in C# 9 as part of 16.10. Tracked by https://github.com/dotnet/roslyn/issues/52630 if (existingMember is null) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: false, diagnostics)); } else if (existingMember is FieldSymbol { IsStatic: false } field && field.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { Binder.CheckFeatureAvailability(syntax, MessageID.IDS_FeaturePositionalFieldsInRecords, diagnostics); if (!isInherited || checkMemberNotHidden(field, param)) { existingOrAddedMembers.Add(field); } } else if (existingMember is PropertySymbol { IsStatic: false, GetMethod: { } } prop && prop.TypeWithAnnotations.Equals(param.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions)) { // There already exists a member corresponding to the candidate synthesized property. if (isInherited && prop.IsAbstract) { addProperty(new SynthesizedRecordPropertySymbol(this, syntax, param, isOverride: true, diagnostics)); } else if (!isInherited || checkMemberNotHidden(prop, param)) { // Deconstruct() is specified to simply assign from this property to the corresponding out parameter. existingOrAddedMembers.Add(prop); } } else { diagnostics.Add(ErrorCode.ERR_BadRecordMemberForPositionalParameter, param.Locations[0], new FormattedSymbol(existingMember, SymbolDisplayFormat.CSharpErrorMessageFormat.WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType)), param.TypeWithAnnotations, param.Name); } void addProperty(SynthesizedRecordPropertySymbol property) { existingOrAddedMembers.Add(property); members.Add(property); Debug.Assert(property.GetMethod is object); Debug.Assert(property.SetMethod is object); members.Add(property.GetMethod); members.Add(property.SetMethod); members.Add(property.BackingField); builder.AddInstanceInitializerForPositionalMembers(new FieldOrPropertyInitializer(property.BackingField, paramList.Parameters[param.Ordinal])); addedCount++; } } return existingOrAddedMembers.ToImmutableAndFree(); bool checkMemberNotHidden(Symbol symbol, ParameterSymbol param) { if (memberNames.Contains(symbol.Name) || this.GetTypeMembersDictionary().ContainsKey(symbol.Name)) { diagnostics.Add(ErrorCode.ERR_HiddenPositionalMember, param.Locations[0], symbol); return false; } return true; } } void addObjectEquals(MethodSymbol thisEquals) { members.Add(new SynthesizedRecordObjEquals(this, thisEquals, memberOffset: members.Count, diagnostics)); } MethodSymbol addGetHashCode(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectGetHashCode, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Int32)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol getHashCode; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingHashCodeMethod)) { getHashCode = new SynthesizedRecordGetHashCode(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(getHashCode); } else { getHashCode = (MethodSymbol)existingHashCodeMethod; if (!SynthesizedRecordObjectMethod.VerifyOverridesMethodFromObject(getHashCode, SpecialMember.System_Object__GetHashCode, diagnostics) && getHashCode.IsSealed && !IsSealed) { diagnostics.Add(ErrorCode.ERR_SealedAPIInRecord, getHashCode.Locations[0], getHashCode); } } return getHashCode; } PropertySymbol addEqualityContract() { Debug.Assert(isRecordClass); var targetProperty = new SignatureOnlyPropertySymbol(SynthesizedRecordEqualityContractProperty.PropertyName, this, ImmutableArray<ParameterSymbol>.Empty, RefKind.None, TypeWithAnnotations.Create(compilation.GetWellKnownType(WellKnownType.System_Type)), ImmutableArray<CustomModifier>.Empty, isStatic: false, ImmutableArray<PropertySymbol>.Empty); PropertySymbol equalityContract; if (!memberSignatures.TryGetValue(targetProperty, out Symbol? existingEqualityContractProperty)) { equalityContract = new SynthesizedRecordEqualityContractProperty(this, diagnostics); members.Add(equalityContract); members.Add(equalityContract.GetMethod); } else { equalityContract = (PropertySymbol)existingEqualityContractProperty; if (this.IsSealed && this.BaseTypeNoUseSiteDiagnostics.IsObjectType()) { if (equalityContract.DeclaredAccessibility != Accessibility.Private) { diagnostics.Add(ErrorCode.ERR_NonPrivateAPIInRecord, equalityContract.Locations[0], equalityContract); } } else if (equalityContract.DeclaredAccessibility != Accessibility.Protected) { diagnostics.Add(ErrorCode.ERR_NonProtectedAPIInRecord, equalityContract.Locations[0], equalityContract); } if (!equalityContract.Type.Equals(targetProperty.Type, TypeCompareKind.AllIgnoreOptions)) { if (!equalityContract.Type.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, equalityContract.Locations[0], equalityContract, targetProperty.Type); } } else { SynthesizedRecordEqualityContractProperty.VerifyOverridesEqualityContractFromBase(equalityContract, diagnostics); } if (equalityContract.GetMethod is null) { diagnostics.Add(ErrorCode.ERR_EqualityContractRequiresGetter, equalityContract.Locations[0], equalityContract); } reportStaticOrNotOverridableAPIInRecord(equalityContract, diagnostics); } return equalityContract; } MethodSymbol addThisEquals(PropertySymbol? equalityContract) { var targetMethod = new SignatureOnlyMethodSymbol( WellKnownMemberNames.ObjectEquals, this, MethodKind.Ordinary, Cci.CallingConvention.HasThis, ImmutableArray<TypeParameterSymbol>.Empty, ImmutableArray.Create<ParameterSymbol>(new SignatureOnlyParameterSymbol( TypeWithAnnotations.Create(this), ImmutableArray<CustomModifier>.Empty, isParams: false, RefKind.None )), RefKind.None, isInitOnly: false, isStatic: false, TypeWithAnnotations.Create(compilation.GetSpecialType(SpecialType.System_Boolean)), ImmutableArray<CustomModifier>.Empty, ImmutableArray<MethodSymbol>.Empty); MethodSymbol thisEquals; if (!memberSignatures.TryGetValue(targetMethod, out Symbol? existingEqualsMethod)) { thisEquals = new SynthesizedRecordEquals(this, equalityContract, memberOffset: members.Count, diagnostics); members.Add(thisEquals); } else { thisEquals = (MethodSymbol)existingEqualsMethod; if (thisEquals.DeclaredAccessibility != Accessibility.Public) { diagnostics.Add(ErrorCode.ERR_NonPublicAPIInRecord, thisEquals.Locations[0], thisEquals); } if (thisEquals.ReturnType.SpecialType != SpecialType.System_Boolean && !thisEquals.ReturnType.IsErrorType()) { diagnostics.Add(ErrorCode.ERR_SignatureMismatchInRecord, thisEquals.Locations[0], thisEquals, targetMethod.ReturnType); } reportStaticOrNotOverridableAPIInRecord(thisEquals, diagnostics); } return thisEquals; } void reportStaticOrNotOverridableAPIInRecord(Symbol symbol, BindingDiagnosticBag diagnostics) { if (isRecordClass && !IsSealed && ((!symbol.IsAbstract && !symbol.IsVirtual && !symbol.IsOverride) || symbol.IsSealed)) { diagnostics.Add(ErrorCode.ERR_NotOverridableAPIInRecord, symbol.Locations[0], symbol); } else if (symbol.IsStatic) { diagnostics.Add(ErrorCode.ERR_StaticAPIInRecord, symbol.Locations[0], symbol); } } void addBaseEquals() { Debug.Assert(isRecordClass); if (!BaseTypeNoUseSiteDiagnostics.IsObjectType()) { members.Add(new SynthesizedRecordBaseEquals(this, memberOffset: members.Count, diagnostics)); } } void addEqualityOperators() { members.Add(new SynthesizedRecordEqualityOperator(this, memberOffset: members.Count, diagnostics)); members.Add(new SynthesizedRecordInequalityOperator(this, memberOffset: members.Count, diagnostics)); } } private void AddSynthesizedConstructorsIfNecessary(MembersAndInitializersBuilder builder, DeclaredMembersAndInitializers declaredMembersAndInitializers, BindingDiagnosticBag diagnostics) { //we're not calling the helpers on NamedTypeSymbol base, because those call //GetMembers and we're inside a GetMembers call ourselves (i.e. stack overflow) var hasInstanceConstructor = false; var hasParameterlessInstanceConstructor = false; var hasStaticConstructor = false; // CONSIDER: if this traversal becomes a bottleneck, the flags could be made outputs of the // dictionary construction process. For now, this is more encapsulated. var membersSoFar = builder.GetNonTypeMembers(declaredMembersAndInitializers); foreach (var member in membersSoFar) { if (member.Kind == SymbolKind.Method) { var method = (MethodSymbol)member; switch (method.MethodKind) { case MethodKind.Constructor: // Ignore the record copy constructor if (!IsRecord || !(SynthesizedRecordCopyCtor.HasCopyConstructorSignature(method) && method is not SynthesizedRecordConstructor)) { hasInstanceConstructor = true; hasParameterlessInstanceConstructor = hasParameterlessInstanceConstructor || method.ParameterCount == 0; } break; case MethodKind.StaticConstructor: hasStaticConstructor = true; break; } } //kick out early if we've seen everything we're looking for if (hasInstanceConstructor && hasStaticConstructor) { break; } } // NOTE: Per section 11.3.8 of the spec, "every struct implicitly has a parameterless instance constructor". // We won't insert a parameterless constructor for a struct if there already is one. // The synthesized constructor will only be emitted if there are field initializers, but it should be in the symbol table. if ((!hasParameterlessInstanceConstructor && this.IsStructType()) || (!hasInstanceConstructor && !this.IsStatic && !this.IsInterface)) { builder.AddNonTypeMember((this.TypeKind == TypeKind.Submission) ? new SynthesizedSubmissionConstructor(this, diagnostics) : new SynthesizedInstanceConstructor(this), declaredMembersAndInitializers); } // constants don't count, since they do not exist as fields at runtime // NOTE: even for decimal constants (which require field initializers), // we do not create .cctor here since a static constructor implicitly created for a decimal // should not appear in the list returned by public API like GetMembers(). if (!hasStaticConstructor && hasNonConstantInitializer(declaredMembersAndInitializers.StaticInitializers)) { // Note: we don't have to put anything in the method - the binder will // do that when processing field initializers. builder.AddNonTypeMember(new SynthesizedStaticConstructor(this), declaredMembersAndInitializers); } if (this.IsScriptClass) { var scriptInitializer = new SynthesizedInteractiveInitializerMethod(this, diagnostics); builder.AddNonTypeMember(scriptInitializer, declaredMembersAndInitializers); var scriptEntryPoint = SynthesizedEntryPointSymbol.Create(scriptInitializer, diagnostics); builder.AddNonTypeMember(scriptEntryPoint, declaredMembersAndInitializers); } static bool hasNonConstantInitializer(ImmutableArray<ImmutableArray<FieldOrPropertyInitializer>> initializers) { return initializers.Any(siblings => siblings.Any(initializer => !initializer.FieldOpt.IsConst)); } } private void AddNonTypeMembers( DeclaredMembersAndInitializersBuilder builder, SyntaxList<MemberDeclarationSyntax> members, BindingDiagnosticBag diagnostics) { if (members.Count == 0) { return; } var firstMember = members[0]; var bodyBinder = this.GetBinder(firstMember); ArrayBuilder<FieldOrPropertyInitializer>? staticInitializers = null; ArrayBuilder<FieldOrPropertyInitializer>? instanceInitializers = null; var compilation = DeclaringCompilation; foreach (var m in members) { if (_lazyMembersAndInitializers != null) { // membersAndInitializers is already computed. no point to continue. return; } bool reportMisplacedGlobalCode = !m.HasErrors; switch (m.Kind()) { case SyntaxKind.FieldDeclaration: { var fieldSyntax = (FieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(fieldSyntax.Declaration.Variables.First().Identifier)); } bool modifierErrors; var modifiers = SourceMemberFieldSymbol.MakeModifiers(this, fieldSyntax.Declaration.Variables[0].Identifier, fieldSyntax.Modifiers, diagnostics, out modifierErrors); foreach (var variable in fieldSyntax.Declaration.Variables) { var fieldSymbol = (modifiers & DeclarationModifiers.Fixed) == 0 ? new SourceMemberFieldSymbolFromDeclarator(this, variable, modifiers, modifierErrors, diagnostics) : new SourceFixedFieldSymbol(this, variable, modifiers, modifierErrors, diagnostics); builder.NonTypeMembers.Add(fieldSymbol); // All fields are included in the nullable context for constructors and initializers, even fields without // initializers, to ensure warnings are reported for uninitialized non-nullable fields in NullableWalker. builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: fieldSymbol.IsStatic, compilation, variable); if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, variable, this, DeclarationModifiers.Private | (modifiers & DeclarationModifiers.Static), fieldSymbol); } if (variable.Initializer != null) { if (fieldSymbol.IsStatic) { AddInitializer(ref staticInitializers, fieldSymbol, variable.Initializer); } else { AddInitializer(ref instanceInitializers, fieldSymbol, variable.Initializer); } } } } break; case SyntaxKind.MethodDeclaration: { var methodSyntax = (MethodDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(methodSyntax.Identifier)); } var method = SourceOrdinaryMethodSymbol.CreateMethodSymbol(this, bodyBinder, methodSyntax, compilation.IsNullableAnalysisEnabledIn(methodSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.ConstructorDeclaration: { var constructorSyntax = (ConstructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(constructorSyntax.Identifier)); } bool isNullableEnabled = compilation.IsNullableAnalysisEnabledIn(constructorSyntax); var constructor = SourceConstructorSymbol.CreateConstructorSymbol(this, constructorSyntax, isNullableEnabled, diagnostics); builder.NonTypeMembers.Add(constructor); if (constructorSyntax.Initializer?.Kind() != SyntaxKind.ThisConstructorInitializer) { builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: constructor.IsStatic, isNullableEnabled); } } break; case SyntaxKind.DestructorDeclaration: { var destructorSyntax = (DestructorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(destructorSyntax.Identifier)); } // CONSIDER: if this doesn't (directly or indirectly) override object.Finalize, the // runtime won't consider it a finalizer and it will not be marked as a destructor // when it is loaded from metadata. Perhaps we should just treat it as an Ordinary // method in such cases? var destructor = new SourceDestructorSymbol(this, destructorSyntax, compilation.IsNullableAnalysisEnabledIn(destructorSyntax), diagnostics); builder.NonTypeMembers.Add(destructor); } break; case SyntaxKind.PropertyDeclaration: { var propertySyntax = (PropertyDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(propertySyntax.Identifier)); } var property = SourcePropertySymbol.Create(this, bodyBinder, propertySyntax, diagnostics); builder.NonTypeMembers.Add(property); AddAccessorIfAvailable(builder.NonTypeMembers, property.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, property.SetMethod); FieldSymbol backingField = property.BackingField; // TODO: can we leave this out of the member list? // From the 10/12/11 design notes: // In addition, we will change autoproperties to behavior in // a similar manner and make the autoproperty fields private. if ((object)backingField != null) { builder.NonTypeMembers.Add(backingField); builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: backingField.IsStatic, compilation, propertySyntax); var initializer = propertySyntax.Initializer; if (initializer != null) { if (IsScriptClass) { // also gather expression-declared variables from the initializer ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, initializer, this, DeclarationModifiers.Private | (property.IsStatic ? DeclarationModifiers.Static : 0), backingField); } if (property.IsStatic) { AddInitializer(ref staticInitializers, backingField, initializer); } else { AddInitializer(ref instanceInitializers, backingField, initializer); } } } } break; case SyntaxKind.EventFieldDeclaration: { var eventFieldSyntax = (EventFieldDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add( ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventFieldSyntax.Declaration.Variables.First().Identifier)); } foreach (VariableDeclaratorSyntax declarator in eventFieldSyntax.Declaration.Variables) { SourceFieldLikeEventSymbol @event = new SourceFieldLikeEventSymbol(this, bodyBinder, eventFieldSyntax.Modifiers, declarator, diagnostics); builder.NonTypeMembers.Add(@event); FieldSymbol? associatedField = @event.AssociatedField; if (IsScriptClass) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, declarator, this, DeclarationModifiers.Private | (@event.IsStatic ? DeclarationModifiers.Static : 0), associatedField); } if ((object?)associatedField != null) { // NOTE: specifically don't add the associated field to the members list // (regard it as an implementation detail). builder.UpdateIsNullableEnabledForConstructorsAndFields(useStatic: associatedField.IsStatic, compilation, declarator); if (declarator.Initializer != null) { if (associatedField.IsStatic) { AddInitializer(ref staticInitializers, associatedField, declarator.Initializer); } else { AddInitializer(ref instanceInitializers, associatedField, declarator.Initializer); } } } Debug.Assert((object)@event.AddMethod != null); Debug.Assert((object)@event.RemoveMethod != null); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); } } break; case SyntaxKind.EventDeclaration: { var eventSyntax = (EventDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(eventSyntax.Identifier)); } var @event = new SourceCustomEventSymbol(this, bodyBinder, eventSyntax, diagnostics); builder.NonTypeMembers.Add(@event); AddAccessorIfAvailable(builder.NonTypeMembers, @event.AddMethod); AddAccessorIfAvailable(builder.NonTypeMembers, @event.RemoveMethod); Debug.Assert(@event.AssociatedField is null); } break; case SyntaxKind.IndexerDeclaration: { var indexerSyntax = (IndexerDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(indexerSyntax.ThisKeyword)); } var indexer = SourcePropertySymbol.Create(this, bodyBinder, indexerSyntax, diagnostics); builder.HaveIndexers = true; builder.NonTypeMembers.Add(indexer); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.GetMethod); AddAccessorIfAvailable(builder.NonTypeMembers, indexer.SetMethod); } break; case SyntaxKind.ConversionOperatorDeclaration: { var conversionOperatorSyntax = (ConversionOperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(conversionOperatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedConversionSymbol.CreateUserDefinedConversionSymbol( this, bodyBinder, conversionOperatorSyntax, compilation.IsNullableAnalysisEnabledIn(conversionOperatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.OperatorDeclaration: { var operatorSyntax = (OperatorDeclarationSyntax)m; if (IsImplicitClass && reportMisplacedGlobalCode) { diagnostics.Add(ErrorCode.ERR_NamespaceUnexpected, new SourceLocation(operatorSyntax.OperatorKeyword)); } var method = SourceUserDefinedOperatorSymbol.CreateUserDefinedOperatorSymbol( this, bodyBinder, operatorSyntax, compilation.IsNullableAnalysisEnabledIn(operatorSyntax), diagnostics); builder.NonTypeMembers.Add(method); } break; case SyntaxKind.GlobalStatement: { var globalStatement = ((GlobalStatementSyntax)m).Statement; if (IsScriptClass) { var innerStatement = globalStatement; // drill into any LabeledStatements while (innerStatement.Kind() == SyntaxKind.LabeledStatement) { innerStatement = ((LabeledStatementSyntax)innerStatement).Statement; } switch (innerStatement.Kind()) { case SyntaxKind.LocalDeclarationStatement: // We shouldn't reach this place, but field declarations preceded with a label end up here. // This is tracked by https://github.com/dotnet/roslyn/issues/13712. Let's do our best for now. var decl = (LocalDeclarationStatementSyntax)innerStatement; foreach (var vdecl in decl.Declaration.Variables) { // also gather expression-declared variables from the bracketed argument lists and the initializers ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, vdecl, this, DeclarationModifiers.Private, containingFieldOpt: null); } break; case SyntaxKind.ExpressionStatement: case SyntaxKind.IfStatement: case SyntaxKind.YieldReturnStatement: case SyntaxKind.ReturnStatement: case SyntaxKind.ThrowStatement: case SyntaxKind.SwitchStatement: case SyntaxKind.LockStatement: ExpressionFieldFinder.FindExpressionVariables(builder.NonTypeMembers, innerStatement, this, DeclarationModifiers.Private, containingFieldOpt: null); break; default: // no other statement introduces variables into the enclosing scope break; } AddInitializer(ref instanceInitializers, null, globalStatement); } else if (reportMisplacedGlobalCode && !SyntaxFacts.IsSimpleProgramTopLevelStatement((GlobalStatementSyntax)m)) { diagnostics.Add(ErrorCode.ERR_GlobalStatement, new SourceLocation(globalStatement)); } } break; default: Debug.Assert( SyntaxFacts.IsTypeDeclaration(m.Kind()) || m.Kind() is SyntaxKind.NamespaceDeclaration or SyntaxKind.FileScopedNamespaceDeclaration or SyntaxKind.IncompleteMember); break; } } AddInitializers(builder.InstanceInitializers, instanceInitializers); AddInitializers(builder.StaticInitializers, staticInitializers); } private void AddAccessorIfAvailable(ArrayBuilder<Symbol> symbols, MethodSymbol? accessorOpt) { if (!(accessorOpt is null)) { symbols.Add(accessorOpt); } } internal override byte? GetLocalNullableContextValue() { byte? value; if (!_flags.TryGetNullableContext(out value)) { value = ComputeNullableContextValue(); _flags.SetNullableContext(value); } return value; } private byte? ComputeNullableContextValue() { var compilation = DeclaringCompilation; if (!compilation.ShouldEmitNullableAttributes(this)) { return null; } var builder = new MostCommonNullableValueBuilder(); var baseType = BaseTypeNoUseSiteDiagnostics; if (baseType is object) { builder.AddValue(TypeWithAnnotations.Create(baseType)); } foreach (var @interface in GetInterfacesToEmit()) { builder.AddValue(TypeWithAnnotations.Create(@interface)); } foreach (var typeParameter in TypeParameters) { typeParameter.GetCommonNullableValues(compilation, ref builder); } foreach (var member in GetMembersUnordered()) { member.GetCommonNullableValues(compilation, ref builder); } // Not including lambdas or local functions. return builder.MostCommonValue; } /// <summary> /// Returns true if the overall nullable context is enabled for constructors and initializers. /// </summary> /// <param name="useStatic">Consider static constructor and fields rather than instance constructors and fields.</param> internal bool IsNullableEnabledForConstructorsAndInitializers(bool useStatic) { var membersAndInitializers = GetMembersAndInitializers(); return useStatic ? membersAndInitializers.IsNullableEnabledForStaticConstructorsAndFields : membersAndInitializers.IsNullableEnabledForInstanceConstructorsAndFields; } internal override void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { base.AddSynthesizedAttributes(moduleBuilder, ref attributes); var compilation = DeclaringCompilation; NamedTypeSymbol baseType = this.BaseTypeNoUseSiteDiagnostics; if (baseType is object) { if (baseType.ContainsDynamic()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeDynamicAttribute(baseType, customModifiersCount: 0)); } if (baseType.ContainsNativeInteger()) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNativeIntegerAttribute(this, baseType)); } if (baseType.ContainsTupleNames()) { AddSynthesizedAttribute(ref attributes, compilation.SynthesizeTupleNamesAttribute(baseType)); } } if (compilation.ShouldEmitNullableAttributes(this)) { if (ShouldEmitNullableContextValue(out byte nullableContextValue)) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableContextAttribute(this, nullableContextValue)); } if (baseType is object) { AddSynthesizedAttribute(ref attributes, moduleBuilder.SynthesizeNullableAttributeIfNecessary(this, nullableContextValue, TypeWithAnnotations.Create(baseType))); } } } #endregion #region Extension Methods internal bool ContainsExtensionMethods { get { if (!_lazyContainsExtensionMethods.HasValue()) { bool containsExtensionMethods = ((this.IsStatic && !this.IsGenericType) || this.IsScriptClass) && this.declaration.ContainsExtensionMethods; _lazyContainsExtensionMethods = containsExtensionMethods.ToThreeState(); } return _lazyContainsExtensionMethods.Value(); } } internal bool AnyMemberHasAttributes { get { if (!_lazyAnyMemberHasAttributes.HasValue()) { bool anyMemberHasAttributes = this.declaration.AnyMemberHasAttributes; _lazyAnyMemberHasAttributes = anyMemberHasAttributes.ToThreeState(); } return _lazyAnyMemberHasAttributes.Value(); } } public override bool MightContainExtensionMethods { get { return this.ContainsExtensionMethods; } } #endregion public sealed override NamedTypeSymbol ConstructedFrom { get { return this; } } internal sealed override bool HasFieldInitializers() => InstanceInitializers.Length > 0; internal class SynthesizedExplicitImplementations { public static readonly SynthesizedExplicitImplementations Empty = new SynthesizedExplicitImplementations(ImmutableArray<SynthesizedExplicitImplementationForwardingMethod>.Empty, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)>.Empty); public readonly ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> ForwardingMethods; public readonly ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> MethodImpls; private SynthesizedExplicitImplementations( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { ForwardingMethods = forwardingMethods.NullToEmpty(); MethodImpls = methodImpls.NullToEmpty(); } internal static SynthesizedExplicitImplementations Create( ImmutableArray<SynthesizedExplicitImplementationForwardingMethod> forwardingMethods, ImmutableArray<(MethodSymbol Body, MethodSymbol Implemented)> methodImpls) { if (forwardingMethods.IsDefaultOrEmpty && methodImpls.IsDefaultOrEmpty) { return Empty; } return new SynthesizedExplicitImplementations(forwardingMethods, methodImpls); } } } }
1
dotnet/roslyn
56,218
Eliminate 75GB allocations during binding in a performance trace
Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
sharwell
"2021-09-07T16:51:03Z"
"2021-09-09T22:25:38Z"
e3e8c6e5196d73d1b7582d40a3c48a22c68e6441
ba2203796b7906d6f53b53bc6fa93f1708e11944
Eliminate 75GB allocations during binding in a performance trace. Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
./src/Compilers/Core/Portable/Compilation/Compilation.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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compilation object is an immutable representation of a single invocation of the /// compiler. Although immutable, a compilation is also on-demand, and will realize and cache /// data as necessary. A compilation can produce a new compilation from existing compilation /// with the application of small deltas. In many cases, it is more efficient than creating a /// new compilation from scratch, as the new compilation can reuse information from the old /// compilation. /// </summary> public abstract partial class Compilation { /// <summary> /// Returns true if this is a case sensitive compilation, false otherwise. Case sensitivity /// affects compilation features such as name lookup as well as choosing what names to emit /// when there are multiple different choices (for example between a virtual method and an /// override). /// </summary> public abstract bool IsCaseSensitive { get; } /// <summary> /// Used for test purposes only to emulate missing members. /// </summary> private SmallDictionary<int, bool>? _lazyMakeWellKnownTypeMissingMap; /// <summary> /// Used for test purposes only to emulate missing members. /// </summary> private SmallDictionary<int, bool>? _lazyMakeMemberMissingMap; // Protected for access in CSharpCompilation.WithAdditionalFeatures protected readonly IReadOnlyDictionary<string, string> _features; public ScriptCompilationInfo? ScriptCompilationInfo => CommonScriptCompilationInfo; internal abstract ScriptCompilationInfo? CommonScriptCompilationInfo { get; } internal Compilation( string? name, ImmutableArray<MetadataReference> references, IReadOnlyDictionary<string, string> features, bool isSubmission, SemanticModelProvider? semanticModelProvider, AsyncQueue<CompilationEvent>? eventQueue) { RoslynDebug.Assert(!references.IsDefault); RoslynDebug.Assert(features != null); this.AssemblyName = name; this.ExternalReferences = references; this.SemanticModelProvider = semanticModelProvider; this.EventQueue = eventQueue; _lazySubmissionSlotIndex = isSubmission ? SubmissionSlotIndexToBeAllocated : SubmissionSlotIndexNotApplicable; _features = features; } protected static IReadOnlyDictionary<string, string> SyntaxTreeCommonFeatures(IEnumerable<SyntaxTree> trees) { IReadOnlyDictionary<string, string>? set = null; foreach (var tree in trees) { var treeFeatures = tree.Options.Features; if (set == null) { set = treeFeatures; } else { if ((object)set != treeFeatures && !set.SetEquals(treeFeatures)) { throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, nameof(trees)); } } } if (set == null) { // Edge case where there are no syntax trees set = ImmutableDictionary<string, string>.Empty; } return set; } internal abstract AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter); /// <summary> /// Gets the source language ("C#" or "Visual Basic"). /// </summary> public abstract string Language { get; } internal abstract void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder); internal static void ValidateScriptCompilationParameters(Compilation? previousScriptCompilation, Type? returnType, ref Type? globalsType) { if (globalsType != null && !IsValidHostObjectType(globalsType)) { throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, nameof(globalsType)); } if (returnType != null && !IsValidSubmissionReturnType(returnType)) { throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, nameof(returnType)); } if (previousScriptCompilation != null) { if (globalsType == null) { globalsType = previousScriptCompilation.HostObjectType; } else if (globalsType != previousScriptCompilation.HostObjectType) { throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, nameof(globalsType)); } // Force the previous submission to be analyzed. This is required for anonymous types unification. if (previousScriptCompilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors); } } } /// <summary> /// Checks options passed to submission compilation constructor. /// Throws an exception if the options are not applicable to submissions. /// </summary> internal static void CheckSubmissionOptions(CompilationOptions? options) { if (options == null) { return; } if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary) { throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, nameof(options)); } if (options.CryptoKeyContainer != null || options.CryptoKeyFile != null || options.DelaySign != null || !options.CryptoPublicKey.IsEmpty || (options.DelaySign == true && options.PublicSign)) { throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, nameof(options)); } } /// <summary> /// Creates a new compilation equivalent to this one with different symbol instances. /// </summary> public Compilation Clone() { return CommonClone(); } protected abstract Compilation CommonClone(); /// <summary> /// Returns a new compilation with a given event queue. /// </summary> internal abstract Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue); /// <summary> /// Returns a new compilation with a given semantic model provider. /// </summary> internal abstract Compilation WithSemanticModelProvider(SemanticModelProvider semanticModelProvider); /// <summary> /// Gets a new <see cref="SemanticModel"/> for the specified syntax tree. /// </summary> /// <param name="syntaxTree">The specified syntax tree.</param> /// <param name="ignoreAccessibility"> /// True if the SemanticModel should ignore accessibility rules when answering semantic questions. /// </param> public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false) => CommonGetSemanticModel(syntaxTree, ignoreAccessibility); /// <summary> /// Gets a <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>. /// If <see cref="SemanticModelProvider"/> is non-null, it attempts to use <see cref="SemanticModelProvider.GetSemanticModel(SyntaxTree, Compilation, bool)"/> /// to get a semantic model. Otherwise, it creates a new semantic model using <see cref="CreateSemanticModel(SyntaxTree, bool)"/>. /// </summary> /// <param name="syntaxTree"></param> /// <param name="ignoreAccessibility"></param> /// <returns></returns> protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility); /// <summary> /// Creates a new <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>. /// Unlike the <see cref="GetSemanticModel(SyntaxTree, bool)"/> and <see cref="CommonGetSemanticModel(SyntaxTree, bool)"/>, /// it does not attempt to use the <see cref="SemanticModelProvider"/> to get a semantic model, but instead always creates a new semantic model. /// </summary> /// <param name="syntaxTree"></param> /// <param name="ignoreAccessibility"></param> /// <returns></returns> internal abstract SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility); /// <summary> /// Returns a new INamedTypeSymbol representing an error type with the given name and arity /// in the given optional container. /// </summary> public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (arity < 0) { throw new ArgumentException($"{nameof(arity)} must be >= 0", nameof(arity)); } return CommonCreateErrorTypeSymbol(container, name, arity); } protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity); /// <summary> /// Returns a new INamespaceSymbol representing an error (missing) namespace with the given name. /// </summary> public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name) { if (container == null) { throw new ArgumentNullException(nameof(container)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } return CommonCreateErrorNamespaceSymbol(container, name); } protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name); #region Name internal const string UnspecifiedModuleAssemblyName = "?"; /// <summary> /// Simple assembly name, or null if not specified. /// </summary> /// <remarks> /// The name is used for determining internals-visible-to relationship with referenced assemblies. /// /// If the compilation represents an assembly the value of <see cref="AssemblyName"/> is its simple name. /// /// Unless <see cref="CompilationOptions.ModuleName"/> specifies otherwise the module name /// written to metadata is <see cref="AssemblyName"/> with an extension based upon <see cref="CompilationOptions.OutputKind"/>. /// </remarks> public string? AssemblyName { get; } internal void CheckAssemblyName(DiagnosticBag diagnostics) { // We could only allow name == null if OutputKind is Module. // However, it does no harm that we allow name == null for assemblies as well, so we don't enforce it. if (this.AssemblyName != null) { MetadataHelpers.CheckAssemblyOrModuleName(this.AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics); } } internal string MakeSourceAssemblySimpleName() { return AssemblyName ?? UnspecifiedModuleAssemblyName; } internal string MakeSourceModuleName() { return Options.ModuleName ?? (AssemblyName != null ? AssemblyName + Options.OutputKind.GetDefaultExtension() : UnspecifiedModuleAssemblyName); } /// <summary> /// Creates a compilation with the specified assembly name. /// </summary> /// <param name="assemblyName">The new assembly name.</param> /// <returns>A new compilation.</returns> public Compilation WithAssemblyName(string? assemblyName) { return CommonWithAssemblyName(assemblyName); } protected abstract Compilation CommonWithAssemblyName(string? outputName); #endregion #region Options /// <summary> /// Gets the options the compilation was created with. /// </summary> public CompilationOptions Options { get { return CommonOptions; } } protected abstract CompilationOptions CommonOptions { get; } /// <summary> /// Creates a new compilation with the specified compilation options. /// </summary> /// <param name="options">The new options.</param> /// <returns>A new compilation.</returns> public Compilation WithOptions(CompilationOptions options) { return CommonWithOptions(options); } protected abstract Compilation CommonWithOptions(CompilationOptions options); #endregion #region Submissions // An index in the submission slot array. Allocated lazily in compilation phase based upon the slot index of the previous submission. // Special values: // -1 ... neither this nor previous submissions in the chain allocated a slot (the submissions don't contain code) // -2 ... the slot of this submission hasn't been determined yet // -3 ... this is not a submission compilation private int _lazySubmissionSlotIndex; private const int SubmissionSlotIndexNotApplicable = -3; private const int SubmissionSlotIndexToBeAllocated = -2; /// <summary> /// True if the compilation represents an interactive submission. /// </summary> internal bool IsSubmission { get { return _lazySubmissionSlotIndex != SubmissionSlotIndexNotApplicable; } } /// <summary> /// The previous submission, if any, or null. /// </summary> private Compilation? PreviousSubmission { get { return ScriptCompilationInfo?.PreviousScriptCompilation; } } /// <summary> /// Gets or allocates a runtime submission slot index for this compilation. /// </summary> /// <returns>Non-negative integer if this is a submission and it or a previous submission contains code, negative integer otherwise.</returns> internal int GetSubmissionSlotIndex() { if (_lazySubmissionSlotIndex == SubmissionSlotIndexToBeAllocated) { // TODO (tomat): remove recursion int lastSlotIndex = ScriptCompilationInfo!.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0; _lazySubmissionSlotIndex = HasCodeToEmit() ? lastSlotIndex + 1 : lastSlotIndex; } return _lazySubmissionSlotIndex; } // The type of interactive submission result requested by the host, or null if this compilation doesn't represent a submission. // // The type is resolved to a symbol when the Script's instance ctor symbol is constructed. The symbol needs to be resolved against // the references of this compilation. // // Consider (tomat): As an alternative to Reflection Type we could hold onto any piece of information that lets us // resolve the type symbol when needed. /// <summary> /// The type object that represents the type of submission result the host requested. /// </summary> internal Type? SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt; internal static bool IsValidSubmissionReturnType(Type type) { return !(type == typeof(void) || type.IsByRef || type.GetTypeInfo().ContainsGenericParameters); } /// <summary> /// The type of the globals object or null if not specified for this compilation. /// </summary> internal Type? HostObjectType => ScriptCompilationInfo?.GlobalsType; internal static bool IsValidHostObjectType(Type type) { var info = type.GetTypeInfo(); return !(info.IsValueType || info.IsPointer || info.IsByRef || info.ContainsGenericParameters); } internal abstract bool HasSubmissionResult(); public Compilation WithScriptCompilationInfo(ScriptCompilationInfo? info) => CommonWithScriptCompilationInfo(info); protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info); #endregion #region Syntax Trees /// <summary> /// Gets the syntax trees (parsed from source code) that this compilation was created with. /// </summary> public IEnumerable<SyntaxTree> SyntaxTrees { get { return CommonSyntaxTrees; } } protected abstract ImmutableArray<SyntaxTree> CommonSyntaxTrees { get; } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation AddSyntaxTrees(params SyntaxTree[] trees) { return CommonAddSyntaxTrees(trees); } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees) { return CommonAddSyntaxTrees(trees); } protected abstract Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees); /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees) { return CommonRemoveSyntaxTrees(trees); } /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees) { return CommonRemoveSyntaxTrees(trees); } protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees); /// <summary> /// Creates a new compilation without any syntax trees. Preserves metadata info for use with /// trees added later. /// </summary> public Compilation RemoveAllSyntaxTrees() { return CommonRemoveAllSyntaxTrees(); } protected abstract Compilation CommonRemoveAllSyntaxTrees(); /// <summary> /// Creates a new compilation with an old syntax tree replaced with a new syntax tree. /// Reuses metadata from old compilation object. /// </summary> /// <param name="newTree">The new tree.</param> /// <param name="oldTree">The old tree.</param> /// <returns>A new compilation.</returns> public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree) { return CommonReplaceSyntaxTree(oldTree, newTree); } protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree); /// <summary> /// Returns true if this compilation contains the specified tree. False otherwise. /// </summary> /// <param name="syntaxTree">A syntax tree.</param> public bool ContainsSyntaxTree(SyntaxTree syntaxTree) { return CommonContainsSyntaxTree(syntaxTree); } protected abstract bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree); /// <summary> /// Optional semantic model provider for this compilation. /// </summary> internal SemanticModelProvider? SemanticModelProvider { get; } /// <summary> /// The event queue that this compilation was created with. /// </summary> internal AsyncQueue<CompilationEvent>? EventQueue { get; } #endregion #region References internal static ImmutableArray<MetadataReference> ValidateReferences<T>(IEnumerable<MetadataReference>? references) where T : CompilationReference { var result = references.AsImmutableOrEmpty(); for (int i = 0; i < result.Length; i++) { var reference = result[i]; if (reference == null) { throw new ArgumentNullException($"{nameof(references)}[{i}]"); } var peReference = reference as PortableExecutableReference; if (peReference == null && !(reference is T)) { Debug.Assert(reference is UnresolvedMetadataReference || reference is CompilationReference); throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, reference.GetType()), $"{nameof(references)}[{i}]"); } } return result; } internal CommonReferenceManager GetBoundReferenceManager() { return CommonGetBoundReferenceManager(); } internal abstract CommonReferenceManager CommonGetBoundReferenceManager(); /// <summary> /// Metadata references passed to the compilation constructor. /// </summary> public ImmutableArray<MetadataReference> ExternalReferences { get; } /// <summary> /// Unique metadata references specified via #r directive in the source code of this compilation. /// </summary> public abstract ImmutableArray<MetadataReference> DirectiveReferences { get; } /// <summary> /// All reference directives used in this compilation. /// </summary> internal abstract IEnumerable<ReferenceDirective> ReferenceDirectives { get; } /// <summary> /// Maps values of #r references to resolved metadata references. /// </summary> internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; } /// <summary> /// All metadata references -- references passed to the compilation /// constructor as well as references specified via #r directives. /// </summary> public IEnumerable<MetadataReference> References { get { foreach (var reference in ExternalReferences) { yield return reference; } foreach (var reference in DirectiveReferences) { yield return reference; } } } /// <summary> /// Creates a metadata reference for this compilation. /// </summary> /// <param name="aliases"> /// Optional aliases that can be used to refer to the compilation root namespace via extern alias directive. /// </param> /// <param name="embedInteropTypes"> /// Embed the COM types from the reference so that the compiled /// application no longer requires a primary interop assembly (PIA). /// </param> public abstract CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false); /// <summary> /// Creates a new compilation with the specified references. /// </summary> /// <param name="newReferences"> /// The new references. /// </param> /// <returns>A new compilation.</returns> public Compilation WithReferences(IEnumerable<MetadataReference> newReferences) { return this.CommonWithReferences(newReferences); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> /// <param name="newReferences">The new references.</param> /// <returns>A new compilation.</returns> public Compilation WithReferences(params MetadataReference[] newReferences) { return this.WithReferences((IEnumerable<MetadataReference>)newReferences); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> protected abstract Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences); /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation AddReferences(params MetadataReference[] references) { return AddReferences((IEnumerable<MetadataReference>)references); } /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation AddReferences(IEnumerable<MetadataReference> references) { if (references == null) { throw new ArgumentNullException(nameof(references)); } if (references.IsEmpty()) { return this; } return CommonWithReferences(this.ExternalReferences.Union(references)); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation RemoveReferences(params MetadataReference[] references) { return RemoveReferences((IEnumerable<MetadataReference>)references); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation RemoveReferences(IEnumerable<MetadataReference> references) { if (references == null) { throw new ArgumentNullException(nameof(references)); } if (references.IsEmpty()) { return this; } var refSet = new HashSet<MetadataReference>(this.ExternalReferences); //EDMAURER if AddingReferences accepts duplicates, then a consumer supplying a list with //duplicates to add will not know exactly which to remove. Let them supply a list with //duplicates here. foreach (var r in references.Distinct()) { if (!refSet.Remove(r)) { throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, r), nameof(references)); } } return CommonWithReferences(refSet); } /// <summary> /// Creates a new compilation without any metadata references. /// </summary> public Compilation RemoveAllReferences() { return CommonWithReferences(SpecializedCollections.EmptyEnumerable<MetadataReference>()); } /// <summary> /// Creates a new compilation with an old metadata reference replaced with a new metadata /// reference. /// </summary> /// <param name="newReference">The new reference.</param> /// <param name="oldReference">The old reference.</param> /// <returns>A new compilation.</returns> public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference? newReference) { if (oldReference == null) { throw new ArgumentNullException(nameof(oldReference)); } if (newReference == null) { return this.RemoveReferences(oldReference); } return this.RemoveReferences(oldReference).AddReferences(newReference); } /// <summary> /// Gets the <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/> for a metadata reference used to create this /// compilation. /// </summary> /// <param name="reference">The target reference.</param> /// <returns> /// Assembly or module symbol corresponding to the given reference or null if there is none. /// </returns> public ISymbol? GetAssemblyOrModuleSymbol(MetadataReference reference) { return CommonGetAssemblyOrModuleSymbol(reference); } protected abstract ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference); /// <summary> /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. /// </summary> /// <param name="assemblySymbol">The target symbol.</param> public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol) { return CommonGetMetadataReference(assemblySymbol); } private protected abstract MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol); /// <summary> /// Assembly identities of all assemblies directly referenced by this compilation. /// </summary> /// <remarks> /// Includes identities of references passed in the compilation constructor /// as well as those specified via directives in source code. /// </remarks> public abstract IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get; } #endregion #region Symbols /// <summary> /// The <see cref="IAssemblySymbol"/> that represents the assembly being created. /// </summary> public IAssemblySymbol Assembly { get { return CommonAssembly; } } protected abstract IAssemblySymbol CommonAssembly { get; } /// <summary> /// Gets the <see cref="IModuleSymbol"/> for the module being created by compiling all of /// the source code. /// </summary> public IModuleSymbol SourceModule { get { return CommonSourceModule; } } protected abstract IModuleSymbol CommonSourceModule { get; } /// <summary> /// The root namespace that contains all namespaces and types defined in source code or in /// referenced metadata, merged into a single namespace hierarchy. /// </summary> public INamespaceSymbol GlobalNamespace { get { return CommonGlobalNamespace; } } protected abstract INamespaceSymbol CommonGlobalNamespace { get; } /// <summary> /// Gets the corresponding compilation namespace for the specified module or assembly namespace. /// </summary> public INamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol) { return CommonGetCompilationNamespace(namespaceSymbol); } protected abstract INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol); internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; } /// <summary> /// Returns the Main method that will serves as the entry point of the assembly, if it is /// executable (and not a script). /// </summary> public IMethodSymbol? GetEntryPoint(CancellationToken cancellationToken) { return CommonGetEntryPoint(cancellationToken); } protected abstract IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken); /// <summary> /// Get the symbol for the predefined type from the Cor Library referenced by this /// compilation. /// </summary> public INamedTypeSymbol GetSpecialType(SpecialType specialType) { return (INamedTypeSymbol)CommonGetSpecialType(specialType).GetITypeSymbol(); } /// <summary> /// Get the symbol for the predefined type member from the COR Library referenced by this compilation. /// </summary> internal abstract ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember); /// <summary> /// Returns true if the type is System.Type. /// </summary> internal abstract bool IsSystemTypeReference(ITypeSymbolInternal type); private protected abstract INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType); /// <summary> /// Lookup member declaration in well known type used by this Compilation. /// </summary> internal abstract ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member); /// <summary> /// Lookup well-known type used by this Compilation. /// </summary> internal abstract ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType); /// <summary> /// Returns true if the specified type is equal to or derives from System.Attribute well-known type. /// </summary> internal abstract bool IsAttributeType(ITypeSymbol type); /// <summary> /// The INamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of /// Error if there was no COR Library in this Compilation. /// </summary> public INamedTypeSymbol ObjectType { get { return CommonObjectType; } } protected abstract INamedTypeSymbol CommonObjectType { get; } /// <summary> /// The TypeSymbol for the type 'dynamic' in this Compilation. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> public ITypeSymbol DynamicType { get { return CommonDynamicType; } } protected abstract ITypeSymbol CommonDynamicType { get; } /// <summary> /// A symbol representing the script globals type. /// </summary> internal ITypeSymbol? ScriptGlobalsType => CommonScriptGlobalsType; protected abstract ITypeSymbol? CommonScriptGlobalsType { get; } /// <summary> /// A symbol representing the implicit Script class. This is null if the class is not /// defined in the compilation. /// </summary> public INamedTypeSymbol? ScriptClass { get { return CommonScriptClass; } } protected abstract INamedTypeSymbol? CommonScriptClass { get; } /// <summary> /// Resolves a symbol that represents script container (Script class). Uses the /// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol. /// </summary> /// <returns>The Script class symbol or null if it is not defined.</returns> protected INamedTypeSymbol? CommonBindScriptClass() { string scriptClassName = this.Options.ScriptClassName ?? ""; string[] parts = scriptClassName.Split('.'); INamespaceSymbol container = this.SourceModule.GlobalNamespace; for (int i = 0; i < parts.Length - 1; i++) { INamespaceSymbol? next = container.GetNestedNamespace(parts[i]); if (next == null) { AssertNoScriptTrees(); return null; } container = next; } foreach (INamedTypeSymbol candidate in container.GetTypeMembers(parts[parts.Length - 1])) { if (candidate.IsScriptClass) { return candidate; } } AssertNoScriptTrees(); return null; } [Conditional("DEBUG")] private void AssertNoScriptTrees() { foreach (var tree in this.CommonSyntaxTrees) { Debug.Assert(tree.Options.Kind != SourceCodeKind.Script); } } /// <summary> /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the /// COR Library in this Compilation. /// </summary> public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None) { return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation); } /// <summary> /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the /// COR Library in this Compilation. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank) { return CreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation: default); } protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation); /// <summary> /// Returns a new IPointerTypeSymbol representing a pointer type tied to a type in this /// Compilation. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType) { return CommonCreatePointerTypeSymbol(pointedAtType); } protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType); /// <summary> /// Returns a new IFunctionPointerTypeSymbol representing a function pointer type tied to types in this /// Compilation. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> /// <exception cref="ArgumentException"> /// If: /// * <see cref="RefKind.Out"/> is passed as the returnRefKind. /// * parameterTypes and parameterRefKinds do not have the same length. /// </exception> /// <exception cref="ArgumentNullException"> /// If returnType is <see langword="null"/>, or if parameterTypes or parameterRefKinds are default, /// or if any of the types in parameterTypes are null.</exception> public IFunctionPointerTypeSymbol CreateFunctionPointerTypeSymbol( ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, SignatureCallingConvention callingConvention = SignatureCallingConvention.Default, ImmutableArray<INamedTypeSymbol> callingConventionTypes = default) { return CommonCreateFunctionPointerTypeSymbol(returnType, returnRefKind, parameterTypes, parameterRefKinds, callingConvention, callingConventionTypes); } protected abstract IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol( ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, SignatureCallingConvention callingConvention, ImmutableArray<INamedTypeSymbol> callingConventionTypes); /// <summary> /// Returns a new INamedTypeSymbol representing a native integer. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> public INamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed) { return CommonCreateNativeIntegerTypeSymbol(signed); } protected abstract INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed); // PERF: ETW Traces show that analyzers may use this method frequently, often requesting // the same symbol over and over again. XUnit analyzers, in particular, were consuming almost // 1% of CPU time when building Roslyn itself. This is an extremely simple cache that evicts on // hash code conflicts, but seems to do the trick. The size is mostly arbitrary. My guess // is that there are maybe a couple dozen analyzers in the solution and each one has // ~0-2 unique well-known types, and the chance of hash collision is very low. private readonly ConcurrentCache<string, INamedTypeSymbol?> _getTypeCache = new ConcurrentCache<string, INamedTypeSymbol?>(50, ReferenceEqualityComparer.Instance); /// <summary> /// Gets the type within the compilation's assembly and all referenced assemblies (other than /// those that can only be referenced via an extern alias) using its canonical CLR metadata name. /// </summary> /// <returns>Null if the type can't be found.</returns> /// <remarks> /// Since VB does not have the concept of extern aliases, it considers all referenced assemblies. /// </remarks> public INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName) { if (!_getTypeCache.TryGetValue(fullyQualifiedMetadataName, out INamedTypeSymbol? val)) { val = CommonGetTypeByMetadataName(fullyQualifiedMetadataName); // Ignore if someone added the same value before us _ = _getTypeCache.TryAdd(fullyQualifiedMetadataName, val); } return val; } protected abstract INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName); #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given element types and /// (optional) element names, locations, and nullable annotations. /// </summary> public INamedTypeSymbol CreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames = default, ImmutableArray<Location?> elementLocations = default, ImmutableArray<NullableAnnotation> elementNullableAnnotations = default) { if (elementTypes.IsDefault) { throw new ArgumentNullException(nameof(elementTypes)); } int n = elementTypes.Length; if (elementTypes.Length <= 1) { throw new ArgumentException(CodeAnalysisResources.TuplesNeedAtLeastTwoElements, nameof(elementNames)); } elementNames = CheckTupleElementNames(n, elementNames); CheckTupleElementLocations(n, elementLocations); CheckTupleElementNullableAnnotations(n, elementNullableAnnotations); for (int i = 0; i < n; i++) { if (elementTypes[i] == null) { throw new ArgumentNullException($"{nameof(elementTypes)}[{i}]"); } if (!elementLocations.IsDefault && elementLocations[i] == null) { throw new ArgumentNullException($"{nameof(elementLocations)}[{i}]"); } } return CommonCreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given element types, names, and locations. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public INamedTypeSymbol CreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations) { return CreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations: default); } protected static void CheckTupleElementNullableAnnotations( int cardinality, ImmutableArray<NullableAnnotation> elementNullableAnnotations) { if (!elementNullableAnnotations.IsDefault) { if (elementNullableAnnotations.Length != cardinality) { throw new ArgumentException(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, nameof(elementNullableAnnotations)); } } } /// <summary> /// Check that if any names are provided, and their number matches the expected cardinality. /// Returns a normalized version of the element names (empty array if all the names are null). /// </summary> protected static ImmutableArray<string?> CheckTupleElementNames(int cardinality, ImmutableArray<string?> elementNames) { if (!elementNames.IsDefault) { if (elementNames.Length != cardinality) { throw new ArgumentException(CodeAnalysisResources.TupleElementNameCountMismatch, nameof(elementNames)); } for (int i = 0; i < elementNames.Length; i++) { if (elementNames[i] == "") { throw new ArgumentException(CodeAnalysisResources.TupleElementNameEmpty, $"{nameof(elementNames)}[{i}]"); } } if (elementNames.All(n => n == null)) { return default; } } return elementNames; } protected static void CheckTupleElementLocations( int cardinality, ImmutableArray<Location?> elementLocations) { if (!elementLocations.IsDefault) { if (elementLocations.Length != cardinality) { throw new ArgumentException(CodeAnalysisResources.TupleElementLocationCountMismatch, nameof(elementLocations)); } } } protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<NullableAnnotation> elementNullableAnnotations); #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given underlying type and /// (optional) element names, locations, and nullable annotations. /// The underlying type needs to be tuple-compatible. /// </summary> public INamedTypeSymbol CreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames = default, ImmutableArray<Location?> elementLocations = default, ImmutableArray<NullableAnnotation> elementNullableAnnotations = default) { if ((object)underlyingType == null) { throw new ArgumentNullException(nameof(underlyingType)); } return CommonCreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given underlying type and element names and locations. /// The underlying type needs to be tuple-compatible. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public INamedTypeSymbol CreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations) { return CreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations: default); } protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<NullableAnnotation> elementNullableAnnotations); /// <summary> /// Returns a new anonymous type symbol with the given member types, names, source locations, and nullable annotations. /// Anonymous type members will be readonly by default. Writable properties are /// supported in VB and can be created by passing in <see langword="false"/> in the /// appropriate locations in <paramref name="memberIsReadOnly"/>. /// </summary> public INamedTypeSymbol CreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<bool> memberIsReadOnly = default, ImmutableArray<Location> memberLocations = default, ImmutableArray<NullableAnnotation> memberNullableAnnotations = default) { if (memberTypes.IsDefault) { throw new ArgumentNullException(nameof(memberTypes)); } if (memberNames.IsDefault) { throw new ArgumentNullException(nameof(memberNames)); } if (memberTypes.Length != memberNames.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeMemberAndNamesCountMismatch2, nameof(memberTypes), nameof(memberNames))); } if (!memberLocations.IsDefault && memberLocations.Length != memberTypes.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, nameof(memberLocations), nameof(memberNames))); } if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Length != memberTypes.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, nameof(memberIsReadOnly), nameof(memberNames))); } if (!memberNullableAnnotations.IsDefault && memberNullableAnnotations.Length != memberTypes.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, nameof(memberNullableAnnotations), nameof(memberNames))); } for (int i = 0, n = memberTypes.Length; i < n; i++) { if (memberTypes[i] == null) { throw new ArgumentNullException($"{nameof(memberTypes)}[{i}]"); } if (memberNames[i] == null) { throw new ArgumentNullException($"{nameof(memberNames)}[{i}]"); } if (!memberLocations.IsDefault && memberLocations[i] == null) { throw new ArgumentNullException($"{nameof(memberLocations)}[{i}]"); } } return CommonCreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations, memberIsReadOnly, memberNullableAnnotations); } /// <summary> /// Returns a new anonymous type symbol with the given member types, names, and source locations. /// Anonymous type members will be readonly by default. Writable properties are /// supported in VB and can be created by passing in <see langword="false"/> in the /// appropriate locations in <paramref name="memberIsReadOnly"/>. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public INamedTypeSymbol CreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<bool> memberIsReadOnly, ImmutableArray<Location> memberLocations) { return CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly, memberLocations, memberNullableAnnotations: default); } protected abstract INamedTypeSymbol CommonCreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<Location> memberLocations, ImmutableArray<bool> memberIsReadOnly, ImmutableArray<NullableAnnotation> memberNullableAnnotations); /// <summary> /// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according /// to this compilation's programming language. /// </summary> /// <param name="source">Source type of value to be converted</param> /// <param name="destination">Destination type of value to be converted</param> /// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the /// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns> public abstract CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination); /// <summary> /// Returns true if there is an implicit (C#) or widening (VB) conversion from /// <paramref name="fromType"/> to <paramref name="toType"/>. Returns false if /// either <paramref name="fromType"/> or <paramref name="toType"/> is null, or /// if no such conversion exists. /// </summary> public bool HasImplicitConversion(ITypeSymbol? fromType, ITypeSymbol? toType) => fromType != null && toType != null && this.ClassifyCommonConversion(fromType, toType).IsImplicit; /// <summary> /// Checks if <paramref name="symbol"/> is accessible from within <paramref name="within"/>. An optional qualifier of type /// <paramref name="throughType"/> is used to resolve protected access for instance members. All symbols are /// required to be from this compilation or some assembly referenced (<see cref="References"/>) by this /// compilation. <paramref name="within"/> is required to be an <see cref="INamedTypeSymbol"/> or <see cref="IAssemblySymbol"/>. /// </summary> /// <remarks> /// <para>Submissions can reference symbols from previous submissions and their referenced assemblies, even /// though those references are missing from <see cref="References"/>. /// See https://github.com/dotnet/roslyn/issues/27356. /// This implementation works around that by permitting symbols from previous submissions as well.</para> /// <para>It is advised to avoid the use of this API within the compilers, as the compilers have additional /// requirements for access checking that are not satisfied by this implementation, including the /// avoidance of infinite recursion that could result from the use of the ISymbol APIs here, the detection /// of use-site diagnostics, and additional returned details (from the compiler's internal APIs) that are /// helpful for more precisely diagnosing reasons for accessibility failure.</para> /// </remarks> public bool IsSymbolAccessibleWithin( ISymbol symbol, ISymbol within, ITypeSymbol? throughType = null) { if (symbol is null) { throw new ArgumentNullException(nameof(symbol)); } if (within is null) { throw new ArgumentNullException(nameof(within)); } if (!(within is INamedTypeSymbol || within is IAssemblySymbol)) { throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleBadWithin, nameof(within)), nameof(within)); } checkInCompilationReferences(symbol, nameof(symbol)); checkInCompilationReferences(within, nameof(within)); if (throughType is object) { checkInCompilationReferences(throughType, nameof(throughType)); } return IsSymbolAccessibleWithinCore(symbol, within, throughType); void checkInCompilationReferences(ISymbol s, string parameterName) { if (!isContainingAssemblyInReferences(s)) { throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleWrongAssembly, parameterName), parameterName); } } bool assemblyIsInReferences(IAssemblySymbol a) { if (assemblyIsInCompilationReferences(a, this)) { return true; } if (this.IsSubmission) { // Submissions can reference symbols from previous submissions and their referenced assemblies, even // though those references are missing from this.References. We work around that by digging in // to find references of previous submissions. See https://github.com/dotnet/roslyn/issues/27356 for (Compilation? c = this.PreviousSubmission; c != null; c = c.PreviousSubmission) { if (assemblyIsInCompilationReferences(a, c)) { return true; } } } return false; } bool assemblyIsInCompilationReferences(IAssemblySymbol a, Compilation compilation) { if (a.Equals(compilation.Assembly)) { return true; } foreach (var reference in compilation.References) { if (a.Equals(compilation.GetAssemblyOrModuleSymbol(reference))) { return true; } } return false; } bool isContainingAssemblyInReferences(ISymbol s) { while (true) { switch (s.Kind) { case SymbolKind.Assembly: return assemblyIsInReferences((IAssemblySymbol)s); case SymbolKind.PointerType: s = ((IPointerTypeSymbol)s).PointedAtType; continue; case SymbolKind.ArrayType: s = ((IArrayTypeSymbol)s).ElementType; continue; case SymbolKind.Alias: s = ((IAliasSymbol)s).Target; continue; case SymbolKind.Discard: s = ((IDiscardSymbol)s).Type; continue; case SymbolKind.FunctionPointerType: var funcPtr = (IFunctionPointerTypeSymbol)s; if (!isContainingAssemblyInReferences(funcPtr.Signature.ReturnType)) { return false; } foreach (var param in funcPtr.Signature.Parameters) { if (!isContainingAssemblyInReferences(param.Type)) { return false; } } return true; case SymbolKind.DynamicType: case SymbolKind.ErrorType: case SymbolKind.Preprocessing: case SymbolKind.Namespace: // these symbols are not restricted in where they can be accessed, so unless they report // a containing assembly, we treat them as in the current assembly for access purposes return assemblyIsInReferences(s.ContainingAssembly ?? this.Assembly); default: return assemblyIsInReferences(s.ContainingAssembly); } } } } private protected abstract bool IsSymbolAccessibleWithinCore( ISymbol symbol, ISymbol within, ITypeSymbol? throughType); internal abstract IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol destination, out ConstantValue? constantValue); #endregion #region Diagnostics internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile; /// <summary> /// Gets the diagnostics produced during the parsing stage. /// </summary> public abstract ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the diagnostics produced during symbol declaration. /// </summary> public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the diagnostics produced during the analysis of method bodies and field initializers. /// </summary> public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the diagnostics for the compilation, including syntax, declaration, and /// binding. Does not include any diagnostics that might be produced during emit, see /// <see cref="EmitResult"/>. /// </summary> public abstract ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); internal abstract void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default); /// <summary> /// Unique metadata assembly references that are considered to be used by this compilation. /// For example, if a type declared in a referenced assembly is referenced in source code /// within this compilation, the reference is considered to be used. Etc. /// The returned set is a subset of references returned by <see cref="References"/> API. /// The result is undefined if the compilation contains errors. /// </summary> public abstract ImmutableArray<MetadataReference> GetUsedAssemblyReferences(CancellationToken cancellationToken = default(CancellationToken)); internal void EnsureCompilationEventQueueCompleted() { RoslynDebug.Assert(EventQueue != null); lock (EventQueue) { if (!EventQueue.IsCompleted) { CompleteCompilationEventQueue_NoLock(); } } } internal void CompleteCompilationEventQueue_NoLock() { RoslynDebug.Assert(EventQueue != null); // Signal the end of compilation. EventQueue.TryEnqueue(new CompilationCompletedEvent(this)); EventQueue.PromiseNotToEnqueue(); EventQueue.TryComplete(); } internal abstract CommonMessageProvider MessageProvider { get; } /// <summary> /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives. /// 'incoming' is freed. /// </summary> /// <param name="accumulator">Bag to which filtered diagnostics will be added.</param> /// <param name="incoming">Diagnostics to be filtered.</param> /// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns> internal bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, [DisallowNull] ref DiagnosticBag? incoming, CancellationToken cancellationToken) { RoslynDebug.Assert(incoming is object); bool result = FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution(), exclude: null, cancellationToken); incoming.Free(); incoming = null; return result; } /// <summary> /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives. /// </summary> /// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns> internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable<Diagnostic> incoming, HashSet<int>? exclude, CancellationToken cancellationToken) { bool hasError = false; bool reportSuppressedDiagnostics = Options.ReportSuppressedDiagnostics; foreach (Diagnostic d in incoming) { if (exclude?.Contains(d.Code) == true) { continue; } var filtered = Options.FilterDiagnostic(d, cancellationToken); if (filtered == null || (!reportSuppressedDiagnostics && filtered.IsSuppressed)) { continue; } else if (filtered.IsUnsuppressableError()) { hasError = true; } accumulator.Add(filtered); } return !hasError; } #endregion #region Resources /// <summary> /// Create a stream filled with default win32 resources. /// </summary> public Stream CreateDefaultWin32Resources(bool versionResource, bool noManifest, Stream? manifestContents, Stream? iconInIcoFormat) { //Win32 resource encodings use a lot of 16bit values. Do all of the math checked with the //expectation that integer types are well-chosen with size in mind. checked { var result = new MemoryStream(1024); //start with a null resource just as rc.exe does AppendNullResource(result); if (versionResource) AppendDefaultVersionResource(result); if (!noManifest) { if (this.Options.OutputKind.IsApplication()) { // Applications use a default manifest if one is not specified. if (manifestContents == null) { manifestContents = typeof(Compilation).GetTypeInfo().Assembly.GetManifestResourceStream("Microsoft.CodeAnalysis.Resources.default.win32manifest"); } } else { // Modules never have manifests, even if one is specified. //Debug.Assert(!this.Options.OutputKind.IsNetModule() || manifestContents == null); } if (manifestContents != null) { Win32ResourceConversions.AppendManifestToResourceStream(result, manifestContents, !this.Options.OutputKind.IsApplication()); } } if (iconInIcoFormat != null) { Win32ResourceConversions.AppendIconToResourceStream(result, iconInIcoFormat); } result.Position = 0; return result; } } internal static void AppendNullResource(Stream resourceStream) { var writer = new BinaryWriter(resourceStream); writer.Write((UInt32)0); writer.Write((UInt32)0x20); writer.Write((UInt16)0xFFFF); writer.Write((UInt16)0); writer.Write((UInt16)0xFFFF); writer.Write((UInt16)0); writer.Write((UInt32)0); //DataVersion writer.Write((UInt16)0); //MemoryFlags writer.Write((UInt16)0); //LanguageId writer.Write((UInt32)0); //Version writer.Write((UInt32)0); //Characteristics } protected abstract void AppendDefaultVersionResource(Stream resourceStream); internal enum Win32ResourceForm : byte { UNKNOWN, COFF, RES } internal static Win32ResourceForm DetectWin32ResourceForm(Stream win32Resources) { var reader = new BinaryReader(win32Resources, Encoding.Unicode); var initialPosition = win32Resources.Position; var initial32Bits = reader.ReadUInt32(); win32Resources.Position = initialPosition; //RC.EXE output starts with a resource that contains no data. if (initial32Bits == 0) return Win32ResourceForm.RES; else if ((initial32Bits & 0xFFFF0000) != 0 || (initial32Bits & 0x0000FFFF) != 0xFFFF) // See CLiteWeightStgdbRW::FindObjMetaData in peparse.cpp return Win32ResourceForm.COFF; else return Win32ResourceForm.UNKNOWN; } internal Cci.ResourceSection? MakeWin32ResourcesFromCOFF(Stream? win32Resources, DiagnosticBag diagnostics) { if (win32Resources == null) { return null; } Cci.ResourceSection resources; try { resources = COFFResourceReader.ReadWin32ResourcesFromCOFF(win32Resources); } catch (BadImageFormatException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } catch (IOException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } catch (ResourceException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } return resources; } internal List<Win32Resource>? MakeWin32ResourceList(Stream? win32Resources, DiagnosticBag diagnostics) { if (win32Resources == null) { return null; } List<RESOURCE> resources; try { resources = CvtResFile.ReadResFile(win32Resources); } catch (ResourceException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } if (resources == null) { return null; } var resourceList = new List<Win32Resource>(); foreach (var r in resources) { var result = new Win32Resource( data: r.data, codePage: 0, languageId: r.LanguageId, //EDMAURER converting to int from ushort. //Go to short first to avoid sign extension. id: unchecked((short)r.pstringName!.Ordinal), name: r.pstringName.theString, typeId: unchecked((short)r.pstringType!.Ordinal), typeName: r.pstringType.theString ); resourceList.Add(result); } return resourceList; } internal void SetupWin32Resources(CommonPEModuleBuilder moduleBeingBuilt, Stream? win32Resources, bool useRawWin32Resources, DiagnosticBag diagnostics) { if (win32Resources == null) return; if (useRawWin32Resources) { moduleBeingBuilt.RawWin32Resources = win32Resources; return; } Win32ResourceForm resourceForm; try { resourceForm = DetectWin32ResourceForm(win32Resources); } catch (EndOfStreamException) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat)); return; } catch (Exception ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, ex.Message)); return; } switch (resourceForm) { case Win32ResourceForm.COFF: moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics); break; case Win32ResourceForm.RES: moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics); break; default: diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat)); break; } } internal void ReportManifestResourceDuplicates( IEnumerable<ResourceDescription>? manifestResources, IEnumerable<string> addedModuleNames, IEnumerable<string> addedModuleResourceNames, DiagnosticBag diagnostics) { if (Options.OutputKind == OutputKind.NetModule && !(manifestResources != null && manifestResources.Any())) { return; } var uniqueResourceNames = new HashSet<string>(); if (manifestResources != null && manifestResources.Any()) { var uniqueFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var resource in manifestResources) { if (!uniqueResourceNames.Add(resource.ResourceName)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, resource.ResourceName)); } // file name could be null if resource is embedded var fileName = resource.FileName; if (fileName != null && !uniqueFileNames.Add(fileName)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName)); } } foreach (var fileName in addedModuleNames) { if (!uniqueFileNames.Add(fileName)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName)); } } } if (Options.OutputKind != OutputKind.NetModule) { foreach (string name in addedModuleResourceNames) { if (!uniqueResourceNames.Add(name)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, name)); } } } } #endregion #region Emit /// <summary> /// There are two ways to sign PE files /// 1. By directly signing the <see cref="PEBuilder"/> /// 2. Write the unsigned PE to disk and use CLR COM APIs to sign. /// The preferred method is #1 as it's more efficient and more resilient (no reliance on %TEMP%). But /// we must continue to support #2 as it's the only way to do the following: /// - Access private keys stored in a key container /// - Do proper counter signature verification for AssemblySignatureKey attributes /// </summary> internal bool SignUsingBuilder => string.IsNullOrEmpty(StrongNameKeys.KeyContainer) && !StrongNameKeys.HasCounterSignature && !_features.ContainsKey("UseLegacyStrongNameProvider"); /// <summary> /// Constructs the module serialization properties out of the compilation options of this compilation. /// </summary> internal Cci.ModulePropertiesForSerialization ConstructModuleSerializationProperties( EmitOptions emitOptions, string? targetRuntimeVersion, Guid moduleVersionId = default(Guid)) { CompilationOptions compilationOptions = this.Options; Platform platform = compilationOptions.Platform; OutputKind outputKind = compilationOptions.OutputKind; if (!platform.IsValid()) { platform = Platform.AnyCpu; } if (!outputKind.IsValid()) { outputKind = OutputKind.DynamicallyLinkedLibrary; } bool requires64Bit = platform.Requires64Bit(); bool requires32Bit = platform.Requires32Bit(); ushort fileAlignment; if (emitOptions.FileAlignment == 0 || !CompilationOptions.IsValidFileAlignment(emitOptions.FileAlignment)) { fileAlignment = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultFileAlignment64Bit : Cci.ModulePropertiesForSerialization.DefaultFileAlignment32Bit; } else { fileAlignment = (ushort)emitOptions.FileAlignment; } ulong baseAddress = unchecked(emitOptions.BaseAddress + 0x8000) & (requires64Bit ? 0xffffffffffff0000 : 0x00000000ffff0000); // cover values smaller than 0x8000, overflow and default value 0): if (baseAddress == 0) { if (outputKind == OutputKind.ConsoleApplication || outputKind == OutputKind.WindowsApplication || outputKind == OutputKind.WindowsRuntimeApplication) { baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit; } else { baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress32Bit; } } ulong sizeOfHeapCommit = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit64Bit : Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit; // Dev10 always uses the default value for 32bit for sizeOfHeapReserve. // check with link -dump -headers <filename> const ulong sizeOfHeapReserve = Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit; ulong sizeOfStackReserve = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve64Bit : Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit; ulong sizeOfStackCommit = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit64Bit : Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit; SubsystemVersion subsystemVersion; if (emitOptions.SubsystemVersion.Equals(SubsystemVersion.None) || !emitOptions.SubsystemVersion.IsValid) { subsystemVersion = SubsystemVersion.Default(outputKind, platform); } else { subsystemVersion = emitOptions.SubsystemVersion; } Machine machine; switch (platform) { case Platform.Arm64: machine = Machine.Arm64; break; case Platform.Arm: machine = Machine.ArmThumb2; break; case Platform.X64: machine = Machine.Amd64; break; case Platform.Itanium: machine = Machine.IA64; break; case Platform.X86: machine = Machine.I386; break; case Platform.AnyCpu: case Platform.AnyCpu32BitPreferred: machine = Machine.Unknown; break; default: throw ExceptionUtilities.UnexpectedValue(platform); } return new Cci.ModulePropertiesForSerialization( persistentIdentifier: moduleVersionId, corFlags: GetCorHeaderFlags(machine, HasStrongName, prefers32Bit: platform == Platform.AnyCpu32BitPreferred), fileAlignment: fileAlignment, sectionAlignment: Cci.ModulePropertiesForSerialization.DefaultSectionAlignment, targetRuntimeVersion: targetRuntimeVersion, machine: machine, baseAddress: baseAddress, sizeOfHeapReserve: sizeOfHeapReserve, sizeOfHeapCommit: sizeOfHeapCommit, sizeOfStackReserve: sizeOfStackReserve, sizeOfStackCommit: sizeOfStackCommit, dllCharacteristics: GetDllCharacteristics(emitOptions.HighEntropyVirtualAddressSpace, compilationOptions.OutputKind == OutputKind.WindowsRuntimeApplication), imageCharacteristics: GetCharacteristics(outputKind, requires32Bit), subsystem: GetSubsystem(outputKind), majorSubsystemVersion: (ushort)subsystemVersion.Major, minorSubsystemVersion: (ushort)subsystemVersion.Minor, linkerMajorVersion: this.LinkerMajorVersion, linkerMinorVersion: 0); } private static CorFlags GetCorHeaderFlags(Machine machine, bool strongNameSigned, bool prefers32Bit) { CorFlags result = CorFlags.ILOnly; if (machine == Machine.I386) { result |= CorFlags.Requires32Bit; } if (strongNameSigned) { result |= CorFlags.StrongNameSigned; } if (prefers32Bit) { result |= CorFlags.Requires32Bit | CorFlags.Prefers32Bit; } return result; } internal static DllCharacteristics GetDllCharacteristics(bool enableHighEntropyVA, bool configureToExecuteInAppContainer) { var result = DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware; if (enableHighEntropyVA) { result |= DllCharacteristics.HighEntropyVirtualAddressSpace; } if (configureToExecuteInAppContainer) { result |= DllCharacteristics.AppContainer; } return result; } private static Characteristics GetCharacteristics(OutputKind outputKind, bool requires32Bit) { var characteristics = Characteristics.ExecutableImage; if (requires32Bit) { // 32 bit machine (The standard says to always set this, the linker team says otherwise) // The loader team says that this is not used for anything in the OS. characteristics |= Characteristics.Bit32Machine; } else { // Large address aware (the standard says never to set this, the linker team says otherwise). // The loader team says that this is not overridden for managed binaries and will be respected if set. characteristics |= Characteristics.LargeAddressAware; } switch (outputKind) { case OutputKind.WindowsRuntimeMetadata: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: characteristics |= Characteristics.Dll; break; case OutputKind.ConsoleApplication: case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsApplication: break; default: throw ExceptionUtilities.UnexpectedValue(outputKind); } return characteristics; } private static Subsystem GetSubsystem(OutputKind outputKind) { switch (outputKind) { case OutputKind.ConsoleApplication: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsRuntimeMetadata: return Subsystem.WindowsCui; case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsApplication: return Subsystem.WindowsGui; default: throw ExceptionUtilities.UnexpectedValue(outputKind); } } /// <summary> /// The value is not used by Windows loader, but the OS appcompat infrastructure uses it to identify apps. /// It is useful for us to have a mechanism to identify the compiler that produced the binary. /// This is the appropriate value to use for that. That is what it was invented for. /// We don't want to have the high bit set for this in case some users perform a signed comparison to /// determine if the value is less than some version. The C++ linker is at 0x0B. /// We'll start our numbering at 0x30 for C#, 0x50 for VB. /// </summary> internal abstract byte LinkerMajorVersion { get; } internal bool HasStrongName { get { return !IsDelaySigned && Options.OutputKind != OutputKind.NetModule && StrongNameKeys.CanProvideStrongName; } } internal bool IsRealSigned { get { // A module cannot be signed. The native compiler allowed one to create a netmodule with an AssemblyKeyFile // or Container attribute (or specify a key via the cmd line). When the module was linked into an assembly, // alink would sign the assembly. So rather than give an error we just don't sign when outputting a module. return !IsDelaySigned && !Options.PublicSign && Options.OutputKind != OutputKind.NetModule && StrongNameKeys.CanSign; } } /// <summary> /// Return true if the compilation contains any code or types. /// </summary> internal abstract bool HasCodeToEmit(); internal abstract bool IsDelaySigned { get; } internal abstract StrongNameKeys StrongNameKeys { get; } internal abstract CommonPEModuleBuilder? CreateModuleBuilder( EmitOptions emitOptions, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, IEnumerable<ResourceDescription>? manifestResources, CompilationTestData? testData, DiagnosticBag diagnostics, CancellationToken cancellationToken); /// <summary> /// Report declaration diagnostics and compile and synthesize method bodies. /// </summary> /// <returns>True if successful.</returns> internal abstract bool CompileMethods( CommonPEModuleBuilder moduleBuilder, bool emittingPdb, bool emitMetadataOnly, bool emitTestCoverageData, DiagnosticBag diagnostics, Predicate<ISymbolInternal>? filterOpt, CancellationToken cancellationToken); internal bool CreateDebugDocuments(DebugDocumentsBuilder documentsBuilder, IEnumerable<EmbeddedText> embeddedTexts, DiagnosticBag diagnostics) { // Check that all syntax trees are debuggable: bool allTreesDebuggable = true; foreach (var tree in CommonSyntaxTrees) { if (!string.IsNullOrEmpty(tree.FilePath) && tree.GetText().Encoding == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncodinglessSyntaxTree, tree.GetRoot().GetLocation())); allTreesDebuggable = false; } } if (!allTreesDebuggable) { return false; } // Add debug documents for all embedded text first. This ensures that embedding // takes priority over the syntax tree pass, which will not embed. if (!embeddedTexts.IsEmpty()) { foreach (var text in embeddedTexts) { Debug.Assert(!string.IsNullOrEmpty(text.FilePath)); string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(text.FilePath, basePath: null); var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath); if (existingDoc == null) { var document = new Cci.DebugSourceDocument( normalizedPath, DebugSourceDocumentLanguageId, () => text.GetDebugSourceInfo()); documentsBuilder.AddDebugDocument(document); } } } // Add debug documents for all trees with distinct paths. foreach (var tree in CommonSyntaxTrees) { if (!string.IsNullOrEmpty(tree.FilePath)) { // compilation does not guarantee that all trees will have distinct paths. // Do not attempt adding a document for a particular path if we already added one. string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(tree.FilePath, basePath: null); var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath); if (existingDoc == null) { documentsBuilder.AddDebugDocument(new Cci.DebugSourceDocument( normalizedPath, DebugSourceDocumentLanguageId, () => tree.GetDebugSourceInfo())); } } } // Add debug documents for all pragmas. // If there are clashes with already processed directives, report warnings. // If there are clashes with debug documents that came from actual trees, ignore the pragma. // Therefore we need to add these in a separate pass after documents for syntax trees were added. foreach (var tree in CommonSyntaxTrees) { AddDebugSourceDocumentsForChecksumDirectives(documentsBuilder, tree, diagnostics); } return true; } internal abstract Guid DebugSourceDocumentLanguageId { get; } internal abstract void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics); /// <summary> /// Update resources and generate XML documentation comments. /// </summary> /// <returns>True if successful.</returns> internal abstract bool GenerateResourcesAndDocumentationComments( CommonPEModuleBuilder moduleBeingBuilt, Stream? xmlDocumentationStream, Stream? win32ResourcesStream, bool useRawWin32Resources, string? outputNameOverride, DiagnosticBag diagnostics, CancellationToken cancellationToken); /// <summary> /// Reports all unused imports/usings so far (and thus it must be called as a last step of Emit) /// </summary> internal abstract void ReportUnusedImports( DiagnosticBag diagnostics, CancellationToken cancellationToken); internal static bool ReportUnusedImportsInTree(SyntaxTree tree) { return tree.Options.DocumentationMode != DocumentationMode.None; } /// <summary> /// Signals the event queue, if any, that we are done compiling. /// There should not be more compiling actions after this step. /// NOTE: once we signal about completion to analyzers they will cancel and thus in some cases we /// may be effectively cutting off some diagnostics. /// It is not clear if behavior is desirable. /// See: https://github.com/dotnet/roslyn/issues/11470 /// </summary> /// <param name="filterTree">What tree to complete. null means complete all trees. </param> internal abstract void CompleteTrees(SyntaxTree? filterTree); internal bool Compile( CommonPEModuleBuilder moduleBuilder, bool emittingPdb, DiagnosticBag diagnostics, Predicate<ISymbolInternal>? filterOpt, CancellationToken cancellationToken) { try { return CompileMethods( moduleBuilder, emittingPdb, emitMetadataOnly: false, emitTestCoverageData: false, diagnostics: diagnostics, filterOpt: filterOpt, cancellationToken: cancellationToken); } finally { moduleBuilder.CompilationFinished(); } } internal void EnsureAnonymousTypeTemplates(CancellationToken cancellationToken) { Debug.Assert(IsSubmission); if (this.GetSubmissionSlotIndex() >= 0 && HasCodeToEmit()) { if (!this.CommonAnonymousTypeManager.AreTemplatesSealed) { var discardedDiagnostics = DiagnosticBag.GetInstance(); var moduleBeingBuilt = this.CreateModuleBuilder( emitOptions: EmitOptions.Default, debugEntryPoint: null, manifestResources: null, sourceLinkStream: null, embeddedTexts: null, testData: null, diagnostics: discardedDiagnostics, cancellationToken: cancellationToken); if (moduleBeingBuilt != null) { Compile( moduleBeingBuilt, diagnostics: discardedDiagnostics, emittingPdb: false, filterOpt: null, cancellationToken: cancellationToken); } discardedDiagnostics.Free(); } Debug.Assert(this.CommonAnonymousTypeManager.AreTemplatesSealed); } else { this.ScriptCompilationInfo?.PreviousScriptCompilation?.EnsureAnonymousTypeTemplates(cancellationToken); } } // 1.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public EmitResult Emit( Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions options, CancellationToken cancellationToken) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, cancellationToken); } // 1.3 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public EmitResult Emit( Stream peStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable<ResourceDescription> manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, CancellationToken cancellationToken) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream: null, embeddedTexts: null, cancellationToken); } // 2.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitResult Emit( Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, CancellationToken cancellationToken) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, metadataPEStream: null, cancellationToken: cancellationToken); } /// <summary> /// Emit the IL for the compiled source code into the specified stream. /// </summary> /// <param name="peStream">Stream to which the compilation will be written.</param> /// <param name="metadataPEStream">Stream to which the metadata-only output will be written.</param> /// <param name="pdbStream">Stream to which the compilation's debug info will be written. Null to forego PDB generation.</param> /// <param name="xmlDocumentationStream">Stream to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32Resources">Stream from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none. The RES format begins with a null resource entry. /// Note that the caller is responsible for disposing this stream, if provided.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="options">Emit options.</param> /// <param name="debugEntryPoint"> /// Debug entry-point of the assembly. The method token is stored in the generated PDB stream. /// /// When a program launches with a debugger attached the debugger places the first breakpoint to the start of the debug entry-point method. /// The CLR starts executing the static Main method of <see cref="CompilationOptions.MainTypeName"/> type. When the first breakpoint is hit /// the debugger steps thru the code statement by statement until user code is reached, skipping methods marked by <see cref="DebuggerHiddenAttribute"/>, /// and taking other debugging attributes into consideration. /// /// By default both entry points in an executable program (<see cref="OutputKind.ConsoleApplication"/>, <see cref="OutputKind.WindowsApplication"/>, <see cref="OutputKind.WindowsRuntimeApplication"/>) /// are the same method (Main). A non-executable program has no entry point. Runtimes that implement a custom loader may specify debug entry-point /// to force the debugger to skip over complex custom loader logic executing at the beginning of the .exe and thus improve debugging experience. /// /// Unlike ordinary entry-point which is limited to a non-generic static method of specific signature, there are no restrictions on the <paramref name="debugEntryPoint"/> /// method other than having a method body (extern, interface, or abstract methods are not allowed). /// </param> /// <param name="sourceLinkStream"> /// Stream containing information linking the compilation to a source control. /// </param> /// <param name="embeddedTexts"> /// Texts to embed in the PDB. /// Only supported when emitting Portable PDBs. /// </param> /// <param name="cancellationToken">To cancel the emit process.</param> public EmitResult Emit( Stream peStream, Stream? pdbStream = null, Stream? xmlDocumentationStream = null, Stream? win32Resources = null, IEnumerable<ResourceDescription>? manifestResources = null, EmitOptions? options = null, IMethodSymbol? debugEntryPoint = null, Stream? sourceLinkStream = null, IEnumerable<EmbeddedText>? embeddedTexts = null, Stream? metadataPEStream = null, CancellationToken cancellationToken = default(CancellationToken)) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, metadataPEStream, rebuildData: null, cancellationToken); } internal EmitResult Emit( Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions? options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, Stream? metadataPEStream, RebuildData? rebuildData, CancellationToken cancellationToken) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanWrite) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(peStream)); } if (pdbStream != null) { if (options?.DebugInformationFormat == DebugInformationFormat.Embedded) { throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmbedding, nameof(pdbStream)); } if (!pdbStream.CanWrite) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(pdbStream)); } if (options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmittingMetadataOnly, nameof(pdbStream)); } } if (metadataPEStream != null && options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.MetadataPeStreamUnexpectedWhenEmittingMetadataOnly, nameof(metadataPEStream)); } if (metadataPEStream != null && options?.IncludePrivateMembers == true) { throw new ArgumentException(CodeAnalysisResources.IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream, nameof(metadataPEStream)); } if (metadataPEStream == null && options?.EmitMetadataOnly == false) { // EmitOptions used to default to IncludePrivateMembers=false, so to preserve binary compatibility we silently correct that unless emitting regular assemblies options = options.WithIncludePrivateMembers(true); } if (options?.DebugInformationFormat == DebugInformationFormat.Embedded && options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.EmbeddingPdbUnexpectedWhenEmittingMetadata, nameof(metadataPEStream)); } if (this.Options.OutputKind == OutputKind.NetModule) { if (metadataPEStream != null) { throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(metadataPEStream)); } else if (options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(options.EmitMetadataOnly)); } } if (win32Resources != null) { if (!win32Resources.CanRead || !win32Resources.CanSeek) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(win32Resources)); } } if (sourceLinkStream != null && !sourceLinkStream.CanRead) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportRead, nameof(sourceLinkStream)); } if (embeddedTexts != null && !embeddedTexts.IsEmpty() && pdbStream == null && options?.DebugInformationFormat != DebugInformationFormat.Embedded) { throw new ArgumentException(CodeAnalysisResources.EmbeddedTextsRequirePdb, nameof(embeddedTexts)); } return Emit( peStream, metadataPEStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, rebuildData, testData: null, cancellationToken: cancellationToken); } /// <summary> /// This overload is only intended to be directly called by tests that want to pass <paramref name="testData"/>. /// The map is used for storing a list of methods and their associated IL. /// </summary> internal EmitResult Emit( Stream peStream, Stream? metadataPEStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions? options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, RebuildData? rebuildData, CompilationTestData? testData, CancellationToken cancellationToken) { options = options ?? EmitOptions.Default.WithIncludePrivateMembers(metadataPEStream == null); bool embedPdb = options.DebugInformationFormat == DebugInformationFormat.Embedded; Debug.Assert(!embedPdb || pdbStream == null); Debug.Assert(metadataPEStream == null || !options.IncludePrivateMembers); // you may not use a secondary stream and include private members together var diagnostics = DiagnosticBag.GetInstance(); var moduleBeingBuilt = CheckOptionsAndCreateModuleBuilder( diagnostics, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, testData, cancellationToken); bool success = false; if (moduleBeingBuilt != null) { try { success = CompileMethods( moduleBeingBuilt, emittingPdb: pdbStream != null || embedPdb, emitMetadataOnly: options.EmitMetadataOnly, emitTestCoverageData: options.EmitTestCoverageData, diagnostics: diagnostics, filterOpt: null, cancellationToken: cancellationToken); if (!options.EmitMetadataOnly) { // NOTE: We generate documentation even in presence of compile errors. // https://github.com/dotnet/roslyn/issues/37996 tracks revisiting this behavior. if (!GenerateResourcesAndDocumentationComments( moduleBeingBuilt, xmlDocumentationStream, win32Resources, useRawWin32Resources: rebuildData is object, options.OutputNameOverride, diagnostics, cancellationToken)) { success = false; } if (success) { ReportUnusedImports(diagnostics, cancellationToken); } } } finally { moduleBeingBuilt.CompilationFinished(); } RSAParameters? privateKeyOpt = null; if (Options.StrongNameProvider != null && SignUsingBuilder && !Options.PublicSign) { privateKeyOpt = StrongNameKeys.PrivateKey; } if (!options.EmitMetadataOnly && CommonCompiler.HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { success = SerializeToPeStream( moduleBeingBuilt, new SimpleEmitStreamProvider(peStream), (metadataPEStream != null) ? new SimpleEmitStreamProvider(metadataPEStream) : null, (pdbStream != null) ? new SimpleEmitStreamProvider(pdbStream) : null, rebuildData, testData?.SymWriterFactory, diagnostics, emitOptions: options, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken); } } return new EmitResult(success, diagnostics.ToReadOnlyAndFree()); } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Emit the differences between the compilation and the previous generation /// for Edit and Continue. The differences are expressed as added and changed /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation /// of the current compilation is returned as an EmitBaseline for use in a /// subsequent Edit and Continue. /// </summary> [Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")] public EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection<MethodDefinitionHandle> updatedMethods, CancellationToken cancellationToken = default(CancellationToken)) { return EmitDifference(baseline, edits, s => false, metadataStream, ilStream, pdbStream, updatedMethods, cancellationToken); } /// <summary> /// Emit the differences between the compilation and the previous generation /// for Edit and Continue. The differences are expressed as added and changed /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation /// of the current compilation is returned as an EmitBaseline for use in a /// subsequent Edit and Continue. /// </summary> [Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")] public EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection<MethodDefinitionHandle> updatedMethods, CancellationToken cancellationToken = default(CancellationToken)) { var diff = EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, cancellationToken); foreach (var token in diff.UpdatedMethods) { updatedMethods.Add(token); } return diff; } /// <summary> /// Emit the differences between the compilation and the previous generation /// for Edit and Continue. The differences are expressed as added and changed /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation /// of the current compilation is returned as an EmitBaseline for use in a /// subsequent Edit and Continue. /// </summary> public EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CancellationToken cancellationToken = default(CancellationToken)) { if (baseline == null) { throw new ArgumentNullException(nameof(baseline)); } // TODO: check if baseline is an assembly manifest module/netmodule // Do we support EnC on netmodules? if (edits == null) { throw new ArgumentNullException(nameof(edits)); } if (isAddedSymbol == null) { throw new ArgumentNullException(nameof(isAddedSymbol)); } if (metadataStream == null) { throw new ArgumentNullException(nameof(metadataStream)); } if (ilStream == null) { throw new ArgumentNullException(nameof(ilStream)); } if (pdbStream == null) { throw new ArgumentNullException(nameof(pdbStream)); } return this.EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData: null, cancellationToken); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters internal abstract EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken); /// <summary> /// Check compilation options and create <see cref="CommonPEModuleBuilder"/>. /// </summary> /// <returns><see cref="CommonPEModuleBuilder"/> if successful.</returns> internal CommonPEModuleBuilder? CheckOptionsAndCreateModuleBuilder( DiagnosticBag diagnostics, IEnumerable<ResourceDescription>? manifestResources, EmitOptions options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, CompilationTestData? testData, CancellationToken cancellationToken) { options.ValidateOptions(diagnostics, MessageProvider, Options.Deterministic); if (debugEntryPoint != null) { ValidateDebugEntryPoint(debugEntryPoint, diagnostics); } if (Options.OutputKind == OutputKind.NetModule && manifestResources != null) { foreach (ResourceDescription res in manifestResources) { if (res.FileName != null) { // Modules can have only embedded resources, not linked ones. diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceInModule, Location.None)); } } } if (CommonCompiler.HasUnsuppressableErrors(diagnostics)) { return null; } // Do not waste a slot in the submission chain for submissions that contain no executable code // (they may only contain #r directives, usings, etc.) if (IsSubmission && !HasCodeToEmit()) { // Still report diagnostics since downstream submissions will assume there are no errors. diagnostics.AddRange(this.GetDiagnostics(cancellationToken)); return null; } return this.CreateModuleBuilder( options, debugEntryPoint, sourceLinkStream, embeddedTexts, manifestResources, testData, diagnostics, cancellationToken); } internal abstract void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics); internal bool IsEmitDeterministic => this.Options.Deterministic; internal bool SerializeToPeStream( CommonPEModuleBuilder moduleBeingBuilt, EmitStreamProvider peStreamProvider, EmitStreamProvider? metadataPEStreamProvider, EmitStreamProvider? pdbStreamProvider, RebuildData? rebuildData, Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory, DiagnosticBag diagnostics, EmitOptions emitOptions, RSAParameters? privateKeyOpt, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Cci.PdbWriter? nativePdbWriter = null; DiagnosticBag? metadataDiagnostics = null; DiagnosticBag? pdbBag = null; bool deterministic = IsEmitDeterministic; // PDB Stream provider should not be given if PDB is to be embedded into the PE file: Debug.Assert(moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Embedded || pdbStreamProvider == null); string? pePdbFilePath = emitOptions.PdbFilePath; if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded || pdbStreamProvider != null) { pePdbFilePath = pePdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"); } else { pePdbFilePath = null; } if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded && !RoslynString.IsNullOrEmpty(pePdbFilePath)) { pePdbFilePath = PathUtilities.GetFileName(pePdbFilePath); } EmitStream? emitPeStream = null; EmitStream? emitMetadataStream = null; try { var signKind = IsRealSigned ? (SignUsingBuilder ? EmitStreamSignKind.SignedWithBuilder : EmitStreamSignKind.SignedWithFile) : EmitStreamSignKind.None; emitPeStream = new EmitStream(peStreamProvider, signKind, Options.StrongNameProvider); emitMetadataStream = metadataPEStreamProvider == null ? null : new EmitStream(metadataPEStreamProvider, signKind, Options.StrongNameProvider); metadataDiagnostics = DiagnosticBag.GetInstance(); if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Pdb && pdbStreamProvider != null) { // The algorithm must be specified for deterministic builds (checked earlier). Debug.Assert(!deterministic || moduleBeingBuilt.PdbChecksumAlgorithm.Name != null); // The calls ISymUnmanagedWriter2.GetDebugInfo require a file name in order to succeed. This is // frequently used during PDB writing. Ensure a name is provided here in the case we were given // only a Stream value. nativePdbWriter = new Cci.PdbWriter(pePdbFilePath, testSymWriterFactory, deterministic ? moduleBeingBuilt.PdbChecksumAlgorithm : default); } Func<Stream?>? getPortablePdbStream = moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.PortablePdb || pdbStreamProvider == null ? null : (Func<Stream?>)(() => ConditionalGetOrCreateStream(pdbStreamProvider, metadataDiagnostics)); try { if (SerializePeToStream( moduleBeingBuilt, metadataDiagnostics, MessageProvider, emitPeStream.GetCreateStreamFunc(metadataDiagnostics), emitMetadataStream?.GetCreateStreamFunc(metadataDiagnostics), getPortablePdbStream, nativePdbWriter, pePdbFilePath, rebuildData, emitOptions.EmitMetadataOnly, emitOptions.IncludePrivateMembers, deterministic, emitOptions.EmitTestCoverageData, privateKeyOpt, cancellationToken)) { if (nativePdbWriter != null) { var nativePdbStream = pdbStreamProvider!.GetOrCreateStream(metadataDiagnostics); Debug.Assert(nativePdbStream != null || metadataDiagnostics.HasAnyErrors()); if (nativePdbStream != null) { nativePdbWriter.WriteTo(nativePdbStream); } } } } catch (SymUnmanagedWriterException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message)); return false; } catch (Cci.PeWritingException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? "")); return false; } catch (ResourceException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_CantReadResource, Location.None, e.Message, e.InnerException?.Message ?? "")); return false; } catch (PermissionSetFileReadException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message)); return false; } // translate metadata errors. if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics, cancellationToken)) { return false; } return emitPeStream.Complete(StrongNameKeys, MessageProvider, diagnostics) && (emitMetadataStream?.Complete(StrongNameKeys, MessageProvider, diagnostics) ?? true); } finally { nativePdbWriter?.Dispose(); emitPeStream?.Close(); emitMetadataStream?.Close(); pdbBag?.Free(); metadataDiagnostics?.Free(); } } private static Stream? ConditionalGetOrCreateStream(EmitStreamProvider metadataPEStreamProvider, DiagnosticBag metadataDiagnostics) { if (metadataDiagnostics.HasAnyErrors()) { return null; } var auxStream = metadataPEStreamProvider.GetOrCreateStream(metadataDiagnostics); Debug.Assert(auxStream != null || metadataDiagnostics.HasAnyErrors()); return auxStream; } internal static bool SerializePeToStream( CommonPEModuleBuilder moduleBeingBuilt, DiagnosticBag metadataDiagnostics, CommonMessageProvider messageProvider, Func<Stream?> getPeStream, Func<Stream?>? getMetadataPeStreamOpt, Func<Stream?>? getPortablePdbStreamOpt, Cci.PdbWriter? nativePdbWriterOpt, string? pdbPathOpt, RebuildData? rebuildData, bool metadataOnly, bool includePrivateMembers, bool isDeterministic, bool emitTestCoverageData, RSAParameters? privateKeyOpt, CancellationToken cancellationToken) { bool emitSecondaryAssembly = getMetadataPeStreamOpt != null; bool includePrivateMembersOnPrimaryOutput = metadataOnly ? includePrivateMembers : true; bool deterministicPrimaryOutput = (metadataOnly && !includePrivateMembers) || isDeterministic; if (!Cci.PeWriter.WritePeToStream( new EmitContext(moduleBeingBuilt, metadataDiagnostics, metadataOnly, includePrivateMembersOnPrimaryOutput, rebuildData: rebuildData), messageProvider, getPeStream, getPortablePdbStreamOpt, nativePdbWriterOpt, pdbPathOpt, metadataOnly, deterministicPrimaryOutput, emitTestCoverageData, privateKeyOpt, cancellationToken)) { return false; } // produce the secondary output (ref assembly) if needed if (emitSecondaryAssembly) { Debug.Assert(!metadataOnly); Debug.Assert(!includePrivateMembers); if (!Cci.PeWriter.WritePeToStream( new EmitContext(moduleBeingBuilt, syntaxNode: null, metadataDiagnostics, metadataOnly: true, includePrivateMembers: false), messageProvider, getMetadataPeStreamOpt, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: true, isDeterministic: true, emitTestCoverageData: false, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken)) { return false; } } return true; } internal EmitBaseline? SerializeToDeltaStreams( CommonPEModuleBuilder moduleBeingBuilt, EmitBaseline baseline, DefinitionMap definitionMap, SymbolChanges changes, Stream metadataStream, Stream ilStream, Stream pdbStream, ArrayBuilder<MethodDefinitionHandle> updatedMethods, ArrayBuilder<TypeDefinitionHandle> changedTypes, DiagnosticBag diagnostics, Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory, string? pdbFilePath, CancellationToken cancellationToken) { var nativePdbWriter = (moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Pdb) ? null : new Cci.PdbWriter( pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"), testSymWriterFactory, hashAlgorithmNameOpt: default); using (nativePdbWriter) { var context = new EmitContext(moduleBeingBuilt, diagnostics, metadataOnly: false, includePrivateMembers: true); var encId = Guid.NewGuid(); try { var writer = new DeltaMetadataWriter( context, MessageProvider, baseline, encId, definitionMap, changes, cancellationToken); writer.WriteMetadataAndIL( nativePdbWriter, metadataStream, ilStream, (nativePdbWriter == null) ? pdbStream : null, out MetadataSizes metadataSizes); writer.GetUpdatedMethodTokens(updatedMethods); writer.GetChangedTypeTokens(changedTypes); nativePdbWriter?.WriteTo(pdbStream); return diagnostics.HasAnyErrors() ? null : writer.GetDelta(this, encId, metadataSizes); } catch (SymUnmanagedWriterException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, e.Message)); return null; } catch (Cci.PeWritingException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? "")); return null; } catch (PermissionSetFileReadException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message)); return null; } } } internal string? Feature(string p) { string? v; return _features.TryGetValue(p, out v) ? v : null; } #endregion private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts>? _lazyTreeToUsedImportDirectivesMap; private static readonly Func<SyntaxTree, SmallConcurrentSetOfInts> s_createSetCallback = t => new SmallConcurrentSetOfInts(); private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts> TreeToUsedImportDirectivesMap { get { return RoslynLazyInitializer.EnsureInitialized(ref _lazyTreeToUsedImportDirectivesMap); } } internal void MarkImportDirectiveAsUsed(SyntaxReference node) { MarkImportDirectiveAsUsed(node.SyntaxTree, node.Span.Start); } internal void MarkImportDirectiveAsUsed(SyntaxTree? syntaxTree, int position) { // Optimization: Don't initialize TreeToUsedImportDirectivesMap in submissions. if (!IsSubmission && syntaxTree != null) { var set = TreeToUsedImportDirectivesMap.GetOrAdd(syntaxTree, s_createSetCallback); set.Add(position); } } internal bool IsImportDirectiveUsed(SyntaxTree syntaxTree, int position) { if (IsSubmission) { // Since usings apply to subsequent submissions, we have to assume they are used. return true; } SmallConcurrentSetOfInts? usedImports; return syntaxTree != null && TreeToUsedImportDirectivesMap.TryGetValue(syntaxTree, out usedImports) && usedImports.Contains(position); } /// <summary> /// The compiler needs to define an ordering among different partial class in different syntax trees /// in some cases, because emit order for fields in structures, for example, is semantically important. /// This function defines an ordering among syntax trees in this compilation. /// </summary> internal int CompareSyntaxTreeOrdering(SyntaxTree tree1, SyntaxTree tree2) { if (tree1 == tree2) { return 0; } Debug.Assert(this.ContainsSyntaxTree(tree1)); Debug.Assert(this.ContainsSyntaxTree(tree2)); return this.GetSyntaxTreeOrdinal(tree1) - this.GetSyntaxTreeOrdinal(tree2); } internal abstract int GetSyntaxTreeOrdinal(SyntaxTree tree); /// <summary> /// Compare two source locations, using their containing trees, and then by Span.First within a tree. /// Can be used to get a total ordering on declarations, for example. /// </summary> internal abstract int CompareSourceLocations(Location loc1, Location loc2); /// <summary> /// Compare two source locations, using their containing trees, and then by Span.First within a tree. /// Can be used to get a total ordering on declarations, for example. /// </summary> internal abstract int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2); /// <summary> /// Return the lexically first of two locations. /// </summary> internal TLocation FirstSourceLocation<TLocation>(TLocation first, TLocation second) where TLocation : Location { if (CompareSourceLocations(first, second) <= 0) { return first; } else { return second; } } /// <summary> /// Return the lexically first of multiple locations. /// </summary> internal TLocation? FirstSourceLocation<TLocation>(ImmutableArray<TLocation> locations) where TLocation : Location { if (locations.IsEmpty) { return null; } var result = locations[0]; for (int i = 1; i < locations.Length; i++) { result = FirstSourceLocation(result, locations[i]); } return result; } #region Logging Helpers // Following helpers are used when logging ETW events. These helpers are invoked only if we are running // under an ETW listener that has requested 'verbose' logging. In other words, these helpers will never // be invoked in the 'normal' case (i.e. when the code is running on user's machine and no ETW listener // is involved). // Note: Most of the below helpers are unused at the moment - but we would like to keep them around in // case we decide we need more verbose logging in certain cases for debugging. internal string GetMessage(CompilationStage stage) { return string.Format("{0} ({1})", this.AssemblyName, stage.ToString()); } internal string GetMessage(ITypeSymbol source, ITypeSymbol destination) { if (source == null || destination == null) return this.AssemblyName ?? ""; return string.Format("{0}: {1} {2} -> {3} {4}", this.AssemblyName, source.TypeKind.ToString(), source.Name, destination.TypeKind.ToString(), destination.Name); } #endregion #region Declaration Name Queries /// <summary> /// Return true if there is a source declaration symbol name that meets given predicate. /// </summary> public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return source declaration symbols whose name meets given predicate. /// </summary> public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Return true if there is a source declaration symbol name that matches the provided name. /// This may be faster than <see cref="ContainsSymbolsWithName(Func{string, bool}, /// SymbolFilter, CancellationToken)"/> when predicate is just a simple string check. /// <paramref name="name"/> is case sensitive or not depending on the target language. /// </summary> public abstract bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return source declaration symbols whose name matches the provided name. This may be /// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter, /// CancellationToken)"/> when predicate is just a simple string check. <paramref /// name="name"/> is case sensitive or not depending on the target language. /// </summary> public abstract IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters #endregion internal void MakeMemberMissing(WellKnownMember member) { MakeMemberMissing((int)member); } internal void MakeMemberMissing(SpecialMember member) { MakeMemberMissing(-(int)member - 1); } internal bool IsMemberMissing(WellKnownMember member) { return IsMemberMissing((int)member); } internal bool IsMemberMissing(SpecialMember member) { return IsMemberMissing(-(int)member - 1); } private void MakeMemberMissing(int member) { if (_lazyMakeMemberMissingMap == null) { _lazyMakeMemberMissingMap = new SmallDictionary<int, bool>(); } _lazyMakeMemberMissingMap[member] = true; } private bool IsMemberMissing(int member) { return _lazyMakeMemberMissingMap != null && _lazyMakeMemberMissingMap.ContainsKey(member); } internal void MakeTypeMissing(SpecialType type) { MakeTypeMissing((int)type); } internal void MakeTypeMissing(WellKnownType type) { MakeTypeMissing((int)type); } private void MakeTypeMissing(int type) { if (_lazyMakeWellKnownTypeMissingMap == null) { _lazyMakeWellKnownTypeMissingMap = new SmallDictionary<int, bool>(); } _lazyMakeWellKnownTypeMissingMap[(int)type] = true; } internal bool IsTypeMissing(SpecialType type) { return IsTypeMissing((int)type); } internal bool IsTypeMissing(WellKnownType type) { return IsTypeMissing((int)type); } private bool IsTypeMissing(int type) { return _lazyMakeWellKnownTypeMissingMap != null && _lazyMakeWellKnownTypeMissingMap.ContainsKey((int)type); } /// <summary> /// Given a <see cref="Diagnostic"/> reporting unreferenced <see cref="AssemblyIdentity"/>s, returns /// the actual <see cref="AssemblyIdentity"/> instances that were not referenced. /// </summary> public ImmutableArray<AssemblyIdentity> GetUnreferencedAssemblyIdentities(Diagnostic diagnostic) { if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } if (!IsUnreferencedAssemblyIdentityDiagnosticCode(diagnostic.Code)) { return ImmutableArray<AssemblyIdentity>.Empty; } var builder = ArrayBuilder<AssemblyIdentity>.GetInstance(); foreach (var argument in diagnostic.Arguments) { if (argument is AssemblyIdentity id) { builder.Add(id); } } return builder.ToImmutableAndFree(); } internal abstract bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code); /// <summary> /// Returns the required language version found in a <see cref="Diagnostic"/>, if any is found. /// Returns null if none is found. /// </summary> public static string? GetRequiredLanguageVersion(Diagnostic diagnostic) { if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } bool found = false; string? foundVersion = null; if (diagnostic.Arguments != null) { foreach (var argument in diagnostic.Arguments) { if (argument is RequiredLanguageVersion versionDiagnostic) { Debug.Assert(!found); // only one required language version in a given diagnostic found = true; foundVersion = versionDiagnostic.ToString(); } } } return foundVersion; } } }
// Licensed to the .NET Foundation under one or more 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.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using System.Security.Cryptography; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// The compilation object is an immutable representation of a single invocation of the /// compiler. Although immutable, a compilation is also on-demand, and will realize and cache /// data as necessary. A compilation can produce a new compilation from existing compilation /// with the application of small deltas. In many cases, it is more efficient than creating a /// new compilation from scratch, as the new compilation can reuse information from the old /// compilation. /// </summary> public abstract partial class Compilation { /// <summary> /// Returns true if this is a case sensitive compilation, false otherwise. Case sensitivity /// affects compilation features such as name lookup as well as choosing what names to emit /// when there are multiple different choices (for example between a virtual method and an /// override). /// </summary> public abstract bool IsCaseSensitive { get; } /// <summary> /// Used for test purposes only to emulate missing members. /// </summary> private SmallDictionary<int, bool>? _lazyMakeWellKnownTypeMissingMap; /// <summary> /// Used for test purposes only to emulate missing members. /// </summary> private SmallDictionary<int, bool>? _lazyMakeMemberMissingMap; // Protected for access in CSharpCompilation.WithAdditionalFeatures protected readonly IReadOnlyDictionary<string, string> _features; public ScriptCompilationInfo? ScriptCompilationInfo => CommonScriptCompilationInfo; internal abstract ScriptCompilationInfo? CommonScriptCompilationInfo { get; } internal Compilation( string? name, ImmutableArray<MetadataReference> references, IReadOnlyDictionary<string, string> features, bool isSubmission, SemanticModelProvider? semanticModelProvider, AsyncQueue<CompilationEvent>? eventQueue) { RoslynDebug.Assert(!references.IsDefault); RoslynDebug.Assert(features != null); this.AssemblyName = name; this.ExternalReferences = references; this.SemanticModelProvider = semanticModelProvider; this.EventQueue = eventQueue; _lazySubmissionSlotIndex = isSubmission ? SubmissionSlotIndexToBeAllocated : SubmissionSlotIndexNotApplicable; _features = features; } protected static IReadOnlyDictionary<string, string> SyntaxTreeCommonFeatures(IEnumerable<SyntaxTree> trees) { IReadOnlyDictionary<string, string>? set = null; foreach (var tree in trees) { var treeFeatures = tree.Options.Features; if (set == null) { set = treeFeatures; } else { if ((object)set != treeFeatures && !set.SetEquals(treeFeatures)) { throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, nameof(trees)); } } } if (set == null) { // Edge case where there are no syntax trees set = ImmutableDictionary<string, string>.Empty; } return set; } internal abstract AnalyzerDriver CreateAnalyzerDriver(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager, SeverityFilter severityFilter); /// <summary> /// Gets the source language ("C#" or "Visual Basic"). /// </summary> public abstract string Language { get; } internal abstract void SerializePdbEmbeddedCompilationOptions(BlobBuilder builder); internal static void ValidateScriptCompilationParameters(Compilation? previousScriptCompilation, Type? returnType, ref Type? globalsType) { if (globalsType != null && !IsValidHostObjectType(globalsType)) { throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, nameof(globalsType)); } if (returnType != null && !IsValidSubmissionReturnType(returnType)) { throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, nameof(returnType)); } if (previousScriptCompilation != null) { if (globalsType == null) { globalsType = previousScriptCompilation.HostObjectType; } else if (globalsType != previousScriptCompilation.HostObjectType) { throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, nameof(globalsType)); } // Force the previous submission to be analyzed. This is required for anonymous types unification. if (previousScriptCompilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error)) { throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors); } } } /// <summary> /// Checks options passed to submission compilation constructor. /// Throws an exception if the options are not applicable to submissions. /// </summary> internal static void CheckSubmissionOptions(CompilationOptions? options) { if (options == null) { return; } if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary) { throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, nameof(options)); } if (options.CryptoKeyContainer != null || options.CryptoKeyFile != null || options.DelaySign != null || !options.CryptoPublicKey.IsEmpty || (options.DelaySign == true && options.PublicSign)) { throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, nameof(options)); } } /// <summary> /// Creates a new compilation equivalent to this one with different symbol instances. /// </summary> public Compilation Clone() { return CommonClone(); } protected abstract Compilation CommonClone(); /// <summary> /// Returns a new compilation with a given event queue. /// </summary> internal abstract Compilation WithEventQueue(AsyncQueue<CompilationEvent>? eventQueue); /// <summary> /// Returns a new compilation with a given semantic model provider. /// </summary> internal abstract Compilation WithSemanticModelProvider(SemanticModelProvider semanticModelProvider); /// <summary> /// Gets a new <see cref="SemanticModel"/> for the specified syntax tree. /// </summary> /// <param name="syntaxTree">The specified syntax tree.</param> /// <param name="ignoreAccessibility"> /// True if the SemanticModel should ignore accessibility rules when answering semantic questions. /// </param> public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false) => CommonGetSemanticModel(syntaxTree, ignoreAccessibility); /// <summary> /// Gets a <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>. /// If <see cref="SemanticModelProvider"/> is non-null, it attempts to use <see cref="SemanticModelProvider.GetSemanticModel(SyntaxTree, Compilation, bool)"/> /// to get a semantic model. Otherwise, it creates a new semantic model using <see cref="CreateSemanticModel(SyntaxTree, bool)"/>. /// </summary> /// <param name="syntaxTree"></param> /// <param name="ignoreAccessibility"></param> /// <returns></returns> protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility); /// <summary> /// Creates a new <see cref="SemanticModel"/> for the given <paramref name="syntaxTree"/>. /// Unlike the <see cref="GetSemanticModel(SyntaxTree, bool)"/> and <see cref="CommonGetSemanticModel(SyntaxTree, bool)"/>, /// it does not attempt to use the <see cref="SemanticModelProvider"/> to get a semantic model, but instead always creates a new semantic model. /// </summary> /// <param name="syntaxTree"></param> /// <param name="ignoreAccessibility"></param> /// <returns></returns> internal abstract SemanticModel CreateSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility); /// <summary> /// Returns a new INamedTypeSymbol representing an error type with the given name and arity /// in the given optional container. /// </summary> public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity) { if (name == null) { throw new ArgumentNullException(nameof(name)); } if (arity < 0) { throw new ArgumentException($"{nameof(arity)} must be >= 0", nameof(arity)); } return CommonCreateErrorTypeSymbol(container, name, arity); } protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol? container, string name, int arity); /// <summary> /// Returns a new INamespaceSymbol representing an error (missing) namespace with the given name. /// </summary> public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name) { if (container == null) { throw new ArgumentNullException(nameof(container)); } if (name == null) { throw new ArgumentNullException(nameof(name)); } return CommonCreateErrorNamespaceSymbol(container, name); } protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name); #region Name internal const string UnspecifiedModuleAssemblyName = "?"; /// <summary> /// Simple assembly name, or null if not specified. /// </summary> /// <remarks> /// The name is used for determining internals-visible-to relationship with referenced assemblies. /// /// If the compilation represents an assembly the value of <see cref="AssemblyName"/> is its simple name. /// /// Unless <see cref="CompilationOptions.ModuleName"/> specifies otherwise the module name /// written to metadata is <see cref="AssemblyName"/> with an extension based upon <see cref="CompilationOptions.OutputKind"/>. /// </remarks> public string? AssemblyName { get; } internal void CheckAssemblyName(DiagnosticBag diagnostics) { // We could only allow name == null if OutputKind is Module. // However, it does no harm that we allow name == null for assemblies as well, so we don't enforce it. if (this.AssemblyName != null) { MetadataHelpers.CheckAssemblyOrModuleName(this.AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics); } } internal string MakeSourceAssemblySimpleName() { return AssemblyName ?? UnspecifiedModuleAssemblyName; } internal string MakeSourceModuleName() { return Options.ModuleName ?? (AssemblyName != null ? AssemblyName + Options.OutputKind.GetDefaultExtension() : UnspecifiedModuleAssemblyName); } /// <summary> /// Creates a compilation with the specified assembly name. /// </summary> /// <param name="assemblyName">The new assembly name.</param> /// <returns>A new compilation.</returns> public Compilation WithAssemblyName(string? assemblyName) { return CommonWithAssemblyName(assemblyName); } protected abstract Compilation CommonWithAssemblyName(string? outputName); #endregion #region Options /// <summary> /// Gets the options the compilation was created with. /// </summary> public CompilationOptions Options { get { return CommonOptions; } } protected abstract CompilationOptions CommonOptions { get; } /// <summary> /// Creates a new compilation with the specified compilation options. /// </summary> /// <param name="options">The new options.</param> /// <returns>A new compilation.</returns> public Compilation WithOptions(CompilationOptions options) { return CommonWithOptions(options); } protected abstract Compilation CommonWithOptions(CompilationOptions options); #endregion #region Submissions // An index in the submission slot array. Allocated lazily in compilation phase based upon the slot index of the previous submission. // Special values: // -1 ... neither this nor previous submissions in the chain allocated a slot (the submissions don't contain code) // -2 ... the slot of this submission hasn't been determined yet // -3 ... this is not a submission compilation private int _lazySubmissionSlotIndex; private const int SubmissionSlotIndexNotApplicable = -3; private const int SubmissionSlotIndexToBeAllocated = -2; /// <summary> /// True if the compilation represents an interactive submission. /// </summary> internal bool IsSubmission { get { return _lazySubmissionSlotIndex != SubmissionSlotIndexNotApplicable; } } /// <summary> /// The previous submission, if any, or null. /// </summary> private Compilation? PreviousSubmission { get { return ScriptCompilationInfo?.PreviousScriptCompilation; } } /// <summary> /// Gets or allocates a runtime submission slot index for this compilation. /// </summary> /// <returns>Non-negative integer if this is a submission and it or a previous submission contains code, negative integer otherwise.</returns> internal int GetSubmissionSlotIndex() { if (_lazySubmissionSlotIndex == SubmissionSlotIndexToBeAllocated) { // TODO (tomat): remove recursion int lastSlotIndex = ScriptCompilationInfo!.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0; _lazySubmissionSlotIndex = HasCodeToEmit() ? lastSlotIndex + 1 : lastSlotIndex; } return _lazySubmissionSlotIndex; } // The type of interactive submission result requested by the host, or null if this compilation doesn't represent a submission. // // The type is resolved to a symbol when the Script's instance ctor symbol is constructed. The symbol needs to be resolved against // the references of this compilation. // // Consider (tomat): As an alternative to Reflection Type we could hold onto any piece of information that lets us // resolve the type symbol when needed. /// <summary> /// The type object that represents the type of submission result the host requested. /// </summary> internal Type? SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt; internal static bool IsValidSubmissionReturnType(Type type) { return !(type == typeof(void) || type.IsByRef || type.GetTypeInfo().ContainsGenericParameters); } /// <summary> /// The type of the globals object or null if not specified for this compilation. /// </summary> internal Type? HostObjectType => ScriptCompilationInfo?.GlobalsType; internal static bool IsValidHostObjectType(Type type) { var info = type.GetTypeInfo(); return !(info.IsValueType || info.IsPointer || info.IsByRef || info.ContainsGenericParameters); } internal abstract bool HasSubmissionResult(); public Compilation WithScriptCompilationInfo(ScriptCompilationInfo? info) => CommonWithScriptCompilationInfo(info); protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo? info); #endregion #region Syntax Trees /// <summary> /// Gets the syntax trees (parsed from source code) that this compilation was created with. /// </summary> public IEnumerable<SyntaxTree> SyntaxTrees { get { return CommonSyntaxTrees; } } protected abstract ImmutableArray<SyntaxTree> CommonSyntaxTrees { get; } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation AddSyntaxTrees(params SyntaxTree[] trees) { return CommonAddSyntaxTrees(trees); } /// <summary> /// Creates a new compilation with additional syntax trees. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees) { return CommonAddSyntaxTrees(trees); } protected abstract Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees); /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees) { return CommonRemoveSyntaxTrees(trees); } /// <summary> /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees /// added later. /// </summary> /// <param name="trees">The new syntax trees.</param> /// <returns>A new compilation.</returns> public Compilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees) { return CommonRemoveSyntaxTrees(trees); } protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees); /// <summary> /// Creates a new compilation without any syntax trees. Preserves metadata info for use with /// trees added later. /// </summary> public Compilation RemoveAllSyntaxTrees() { return CommonRemoveAllSyntaxTrees(); } protected abstract Compilation CommonRemoveAllSyntaxTrees(); /// <summary> /// Creates a new compilation with an old syntax tree replaced with a new syntax tree. /// Reuses metadata from old compilation object. /// </summary> /// <param name="newTree">The new tree.</param> /// <param name="oldTree">The old tree.</param> /// <returns>A new compilation.</returns> public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree) { return CommonReplaceSyntaxTree(oldTree, newTree); } protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree); /// <summary> /// Returns true if this compilation contains the specified tree. False otherwise. /// </summary> /// <param name="syntaxTree">A syntax tree.</param> public bool ContainsSyntaxTree(SyntaxTree syntaxTree) { return CommonContainsSyntaxTree(syntaxTree); } protected abstract bool CommonContainsSyntaxTree(SyntaxTree? syntaxTree); /// <summary> /// Optional semantic model provider for this compilation. /// </summary> internal SemanticModelProvider? SemanticModelProvider { get; } /// <summary> /// The event queue that this compilation was created with. /// </summary> internal AsyncQueue<CompilationEvent>? EventQueue { get; } #endregion #region References internal static ImmutableArray<MetadataReference> ValidateReferences<T>(IEnumerable<MetadataReference>? references) where T : CompilationReference { var result = references.AsImmutableOrEmpty(); for (int i = 0; i < result.Length; i++) { var reference = result[i]; if (reference == null) { throw new ArgumentNullException($"{nameof(references)}[{i}]"); } var peReference = reference as PortableExecutableReference; if (peReference == null && !(reference is T)) { Debug.Assert(reference is UnresolvedMetadataReference || reference is CompilationReference); throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, reference.GetType()), $"{nameof(references)}[{i}]"); } } return result; } internal CommonReferenceManager GetBoundReferenceManager() { return CommonGetBoundReferenceManager(); } internal abstract CommonReferenceManager CommonGetBoundReferenceManager(); /// <summary> /// Metadata references passed to the compilation constructor. /// </summary> public ImmutableArray<MetadataReference> ExternalReferences { get; } /// <summary> /// Unique metadata references specified via #r directive in the source code of this compilation. /// </summary> public abstract ImmutableArray<MetadataReference> DirectiveReferences { get; } /// <summary> /// All reference directives used in this compilation. /// </summary> internal abstract IEnumerable<ReferenceDirective> ReferenceDirectives { get; } /// <summary> /// Maps values of #r references to resolved metadata references. /// </summary> internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; } /// <summary> /// All metadata references -- references passed to the compilation /// constructor as well as references specified via #r directives. /// </summary> public IEnumerable<MetadataReference> References { get { foreach (var reference in ExternalReferences) { yield return reference; } foreach (var reference in DirectiveReferences) { yield return reference; } } } /// <summary> /// Creates a metadata reference for this compilation. /// </summary> /// <param name="aliases"> /// Optional aliases that can be used to refer to the compilation root namespace via extern alias directive. /// </param> /// <param name="embedInteropTypes"> /// Embed the COM types from the reference so that the compiled /// application no longer requires a primary interop assembly (PIA). /// </param> public abstract CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false); /// <summary> /// Creates a new compilation with the specified references. /// </summary> /// <param name="newReferences"> /// The new references. /// </param> /// <returns>A new compilation.</returns> public Compilation WithReferences(IEnumerable<MetadataReference> newReferences) { return this.CommonWithReferences(newReferences); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> /// <param name="newReferences">The new references.</param> /// <returns>A new compilation.</returns> public Compilation WithReferences(params MetadataReference[] newReferences) { return this.WithReferences((IEnumerable<MetadataReference>)newReferences); } /// <summary> /// Creates a new compilation with the specified references. /// </summary> protected abstract Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences); /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation AddReferences(params MetadataReference[] references) { return AddReferences((IEnumerable<MetadataReference>)references); } /// <summary> /// Creates a new compilation with additional metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation AddReferences(IEnumerable<MetadataReference> references) { if (references == null) { throw new ArgumentNullException(nameof(references)); } if (references.IsEmpty()) { return this; } return CommonWithReferences(this.ExternalReferences.Union(references)); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation RemoveReferences(params MetadataReference[] references) { return RemoveReferences((IEnumerable<MetadataReference>)references); } /// <summary> /// Creates a new compilation without the specified metadata references. /// </summary> /// <param name="references">The new references.</param> /// <returns>A new compilation.</returns> public Compilation RemoveReferences(IEnumerable<MetadataReference> references) { if (references == null) { throw new ArgumentNullException(nameof(references)); } if (references.IsEmpty()) { return this; } var refSet = new HashSet<MetadataReference>(this.ExternalReferences); //EDMAURER if AddingReferences accepts duplicates, then a consumer supplying a list with //duplicates to add will not know exactly which to remove. Let them supply a list with //duplicates here. foreach (var r in references.Distinct()) { if (!refSet.Remove(r)) { throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, r), nameof(references)); } } return CommonWithReferences(refSet); } /// <summary> /// Creates a new compilation without any metadata references. /// </summary> public Compilation RemoveAllReferences() { return CommonWithReferences(SpecializedCollections.EmptyEnumerable<MetadataReference>()); } /// <summary> /// Creates a new compilation with an old metadata reference replaced with a new metadata /// reference. /// </summary> /// <param name="newReference">The new reference.</param> /// <param name="oldReference">The old reference.</param> /// <returns>A new compilation.</returns> public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference? newReference) { if (oldReference == null) { throw new ArgumentNullException(nameof(oldReference)); } if (newReference == null) { return this.RemoveReferences(oldReference); } return this.RemoveReferences(oldReference).AddReferences(newReference); } /// <summary> /// Gets the <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/> for a metadata reference used to create this /// compilation. /// </summary> /// <param name="reference">The target reference.</param> /// <returns> /// Assembly or module symbol corresponding to the given reference or null if there is none. /// </returns> public ISymbol? GetAssemblyOrModuleSymbol(MetadataReference reference) { return CommonGetAssemblyOrModuleSymbol(reference); } protected abstract ISymbol? CommonGetAssemblyOrModuleSymbol(MetadataReference reference); /// <summary> /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. /// </summary> /// <param name="assemblySymbol">The target symbol.</param> public MetadataReference? GetMetadataReference(IAssemblySymbol assemblySymbol) { return CommonGetMetadataReference(assemblySymbol); } private protected abstract MetadataReference? CommonGetMetadataReference(IAssemblySymbol assemblySymbol); /// <summary> /// Assembly identities of all assemblies directly referenced by this compilation. /// </summary> /// <remarks> /// Includes identities of references passed in the compilation constructor /// as well as those specified via directives in source code. /// </remarks> public abstract IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get; } #endregion #region Symbols /// <summary> /// The <see cref="IAssemblySymbol"/> that represents the assembly being created. /// </summary> public IAssemblySymbol Assembly { get { return CommonAssembly; } } protected abstract IAssemblySymbol CommonAssembly { get; } /// <summary> /// Gets the <see cref="IModuleSymbol"/> for the module being created by compiling all of /// the source code. /// </summary> public IModuleSymbol SourceModule { get { return CommonSourceModule; } } protected abstract IModuleSymbol CommonSourceModule { get; } /// <summary> /// The root namespace that contains all namespaces and types defined in source code or in /// referenced metadata, merged into a single namespace hierarchy. /// </summary> public INamespaceSymbol GlobalNamespace { get { return CommonGlobalNamespace; } } protected abstract INamespaceSymbol CommonGlobalNamespace { get; } /// <summary> /// Gets the corresponding compilation namespace for the specified module or assembly namespace. /// </summary> public INamespaceSymbol? GetCompilationNamespace(INamespaceSymbol namespaceSymbol) { return CommonGetCompilationNamespace(namespaceSymbol); } protected abstract INamespaceSymbol? CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol); internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; } /// <summary> /// Returns the Main method that will serves as the entry point of the assembly, if it is /// executable (and not a script). /// </summary> public IMethodSymbol? GetEntryPoint(CancellationToken cancellationToken) { return CommonGetEntryPoint(cancellationToken); } protected abstract IMethodSymbol? CommonGetEntryPoint(CancellationToken cancellationToken); /// <summary> /// Get the symbol for the predefined type from the Cor Library referenced by this /// compilation. /// </summary> public INamedTypeSymbol GetSpecialType(SpecialType specialType) { return (INamedTypeSymbol)CommonGetSpecialType(specialType).GetITypeSymbol(); } /// <summary> /// Get the symbol for the predefined type member from the COR Library referenced by this compilation. /// </summary> internal abstract ISymbolInternal CommonGetSpecialTypeMember(SpecialMember specialMember); /// <summary> /// Returns true if the type is System.Type. /// </summary> internal abstract bool IsSystemTypeReference(ITypeSymbolInternal type); private protected abstract INamedTypeSymbolInternal CommonGetSpecialType(SpecialType specialType); /// <summary> /// Lookup member declaration in well known type used by this Compilation. /// </summary> internal abstract ISymbolInternal? CommonGetWellKnownTypeMember(WellKnownMember member); /// <summary> /// Lookup well-known type used by this Compilation. /// </summary> internal abstract ITypeSymbolInternal CommonGetWellKnownType(WellKnownType wellknownType); /// <summary> /// Returns true if the specified type is equal to or derives from System.Attribute well-known type. /// </summary> internal abstract bool IsAttributeType(ITypeSymbol type); /// <summary> /// The INamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of /// Error if there was no COR Library in this Compilation. /// </summary> public INamedTypeSymbol ObjectType { get { return CommonObjectType; } } protected abstract INamedTypeSymbol CommonObjectType { get; } /// <summary> /// The TypeSymbol for the type 'dynamic' in this Compilation. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> public ITypeSymbol DynamicType { get { return CommonDynamicType; } } protected abstract ITypeSymbol CommonDynamicType { get; } /// <summary> /// A symbol representing the script globals type. /// </summary> internal ITypeSymbol? ScriptGlobalsType => CommonScriptGlobalsType; protected abstract ITypeSymbol? CommonScriptGlobalsType { get; } /// <summary> /// A symbol representing the implicit Script class. This is null if the class is not /// defined in the compilation. /// </summary> public INamedTypeSymbol? ScriptClass { get { return CommonScriptClass; } } protected abstract INamedTypeSymbol? CommonScriptClass { get; } /// <summary> /// Resolves a symbol that represents script container (Script class). Uses the /// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol. /// </summary> /// <returns>The Script class symbol or null if it is not defined.</returns> protected INamedTypeSymbol? CommonBindScriptClass() { string scriptClassName = this.Options.ScriptClassName ?? ""; string[] parts = scriptClassName.Split('.'); INamespaceSymbol container = this.SourceModule.GlobalNamespace; for (int i = 0; i < parts.Length - 1; i++) { INamespaceSymbol? next = container.GetNestedNamespace(parts[i]); if (next == null) { AssertNoScriptTrees(); return null; } container = next; } foreach (INamedTypeSymbol candidate in container.GetTypeMembers(parts[parts.Length - 1])) { if (candidate.IsScriptClass) { return candidate; } } AssertNoScriptTrees(); return null; } [Conditional("DEBUG")] private void AssertNoScriptTrees() { foreach (var tree in this.CommonSyntaxTrees) { Debug.Assert(tree.Options.Kind != SourceCodeKind.Script); } } /// <summary> /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the /// COR Library in this Compilation. /// </summary> public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None) { return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation); } /// <summary> /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the /// COR Library in this Compilation. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank) { return CreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation: default); } protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation); /// <summary> /// Returns a new IPointerTypeSymbol representing a pointer type tied to a type in this /// Compilation. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType) { return CommonCreatePointerTypeSymbol(pointedAtType); } protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType); /// <summary> /// Returns a new IFunctionPointerTypeSymbol representing a function pointer type tied to types in this /// Compilation. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> /// <exception cref="ArgumentException"> /// If: /// * <see cref="RefKind.Out"/> is passed as the returnRefKind. /// * parameterTypes and parameterRefKinds do not have the same length. /// </exception> /// <exception cref="ArgumentNullException"> /// If returnType is <see langword="null"/>, or if parameterTypes or parameterRefKinds are default, /// or if any of the types in parameterTypes are null.</exception> public IFunctionPointerTypeSymbol CreateFunctionPointerTypeSymbol( ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, SignatureCallingConvention callingConvention = SignatureCallingConvention.Default, ImmutableArray<INamedTypeSymbol> callingConventionTypes = default) { return CommonCreateFunctionPointerTypeSymbol(returnType, returnRefKind, parameterTypes, parameterRefKinds, callingConvention, callingConventionTypes); } protected abstract IFunctionPointerTypeSymbol CommonCreateFunctionPointerTypeSymbol( ITypeSymbol returnType, RefKind returnRefKind, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, SignatureCallingConvention callingConvention, ImmutableArray<INamedTypeSymbol> callingConventionTypes); /// <summary> /// Returns a new INamedTypeSymbol representing a native integer. /// </summary> /// <exception cref="NotSupportedException">If the compilation is a VisualBasic compilation.</exception> public INamedTypeSymbol CreateNativeIntegerTypeSymbol(bool signed) { return CommonCreateNativeIntegerTypeSymbol(signed); } protected abstract INamedTypeSymbol CommonCreateNativeIntegerTypeSymbol(bool signed); // PERF: ETW Traces show that analyzers may use this method frequently, often requesting // the same symbol over and over again. XUnit analyzers, in particular, were consuming almost // 1% of CPU time when building Roslyn itself. This is an extremely simple cache that evicts on // hash code conflicts, but seems to do the trick. The size is mostly arbitrary. My guess // is that there are maybe a couple dozen analyzers in the solution and each one has // ~0-2 unique well-known types, and the chance of hash collision is very low. private readonly ConcurrentCache<string, INamedTypeSymbol?> _getTypeCache = new ConcurrentCache<string, INamedTypeSymbol?>(50, ReferenceEqualityComparer.Instance); /// <summary> /// Gets the type within the compilation's assembly and all referenced assemblies (other than /// those that can only be referenced via an extern alias) using its canonical CLR metadata name. /// </summary> /// <returns>Null if the type can't be found.</returns> /// <remarks> /// Since VB does not have the concept of extern aliases, it considers all referenced assemblies. /// </remarks> public INamedTypeSymbol? GetTypeByMetadataName(string fullyQualifiedMetadataName) { if (!_getTypeCache.TryGetValue(fullyQualifiedMetadataName, out INamedTypeSymbol? val)) { val = CommonGetTypeByMetadataName(fullyQualifiedMetadataName); // Ignore if someone added the same value before us _ = _getTypeCache.TryAdd(fullyQualifiedMetadataName, val); } return val; } protected abstract INamedTypeSymbol? CommonGetTypeByMetadataName(string metadataName); #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given element types and /// (optional) element names, locations, and nullable annotations. /// </summary> public INamedTypeSymbol CreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames = default, ImmutableArray<Location?> elementLocations = default, ImmutableArray<NullableAnnotation> elementNullableAnnotations = default) { if (elementTypes.IsDefault) { throw new ArgumentNullException(nameof(elementTypes)); } int n = elementTypes.Length; if (elementTypes.Length <= 1) { throw new ArgumentException(CodeAnalysisResources.TuplesNeedAtLeastTwoElements, nameof(elementNames)); } elementNames = CheckTupleElementNames(n, elementNames); CheckTupleElementLocations(n, elementLocations); CheckTupleElementNullableAnnotations(n, elementNullableAnnotations); for (int i = 0; i < n; i++) { if (elementTypes[i] == null) { throw new ArgumentNullException($"{nameof(elementTypes)}[{i}]"); } if (!elementLocations.IsDefault && elementLocations[i] == null) { throw new ArgumentNullException($"{nameof(elementLocations)}[{i}]"); } } return CommonCreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given element types, names, and locations. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public INamedTypeSymbol CreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations) { return CreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations: default); } protected static void CheckTupleElementNullableAnnotations( int cardinality, ImmutableArray<NullableAnnotation> elementNullableAnnotations) { if (!elementNullableAnnotations.IsDefault) { if (elementNullableAnnotations.Length != cardinality) { throw new ArgumentException(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, nameof(elementNullableAnnotations)); } } } /// <summary> /// Check that if any names are provided, and their number matches the expected cardinality. /// Returns a normalized version of the element names (empty array if all the names are null). /// </summary> protected static ImmutableArray<string?> CheckTupleElementNames(int cardinality, ImmutableArray<string?> elementNames) { if (!elementNames.IsDefault) { if (elementNames.Length != cardinality) { throw new ArgumentException(CodeAnalysisResources.TupleElementNameCountMismatch, nameof(elementNames)); } for (int i = 0; i < elementNames.Length; i++) { if (elementNames[i] == "") { throw new ArgumentException(CodeAnalysisResources.TupleElementNameEmpty, $"{nameof(elementNames)}[{i}]"); } } if (elementNames.All(n => n == null)) { return default; } } return elementNames; } protected static void CheckTupleElementLocations( int cardinality, ImmutableArray<Location?> elementLocations) { if (!elementLocations.IsDefault) { if (elementLocations.Length != cardinality) { throw new ArgumentException(CodeAnalysisResources.TupleElementLocationCountMismatch, nameof(elementLocations)); } } } protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol( ImmutableArray<ITypeSymbol> elementTypes, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<NullableAnnotation> elementNullableAnnotations); #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given underlying type and /// (optional) element names, locations, and nullable annotations. /// The underlying type needs to be tuple-compatible. /// </summary> public INamedTypeSymbol CreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames = default, ImmutableArray<Location?> elementLocations = default, ImmutableArray<NullableAnnotation> elementNullableAnnotations = default) { if ((object)underlyingType == null) { throw new ArgumentNullException(nameof(underlyingType)); } return CommonCreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Returns a new INamedTypeSymbol with the given underlying type and element names and locations. /// The underlying type needs to be tuple-compatible. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public INamedTypeSymbol CreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations) { return CreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations: default); } protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol( INamedTypeSymbol underlyingType, ImmutableArray<string?> elementNames, ImmutableArray<Location?> elementLocations, ImmutableArray<NullableAnnotation> elementNullableAnnotations); /// <summary> /// Returns a new anonymous type symbol with the given member types, names, source locations, and nullable annotations. /// Anonymous type members will be readonly by default. Writable properties are /// supported in VB and can be created by passing in <see langword="false"/> in the /// appropriate locations in <paramref name="memberIsReadOnly"/>. /// </summary> public INamedTypeSymbol CreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<bool> memberIsReadOnly = default, ImmutableArray<Location> memberLocations = default, ImmutableArray<NullableAnnotation> memberNullableAnnotations = default) { if (memberTypes.IsDefault) { throw new ArgumentNullException(nameof(memberTypes)); } if (memberNames.IsDefault) { throw new ArgumentNullException(nameof(memberNames)); } if (memberTypes.Length != memberNames.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeMemberAndNamesCountMismatch2, nameof(memberTypes), nameof(memberNames))); } if (!memberLocations.IsDefault && memberLocations.Length != memberTypes.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, nameof(memberLocations), nameof(memberNames))); } if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Length != memberTypes.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, nameof(memberIsReadOnly), nameof(memberNames))); } if (!memberNullableAnnotations.IsDefault && memberNullableAnnotations.Length != memberTypes.Length) { throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2, nameof(memberNullableAnnotations), nameof(memberNames))); } for (int i = 0, n = memberTypes.Length; i < n; i++) { if (memberTypes[i] == null) { throw new ArgumentNullException($"{nameof(memberTypes)}[{i}]"); } if (memberNames[i] == null) { throw new ArgumentNullException($"{nameof(memberNames)}[{i}]"); } if (!memberLocations.IsDefault && memberLocations[i] == null) { throw new ArgumentNullException($"{nameof(memberLocations)}[{i}]"); } } return CommonCreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations, memberIsReadOnly, memberNullableAnnotations); } /// <summary> /// Returns a new anonymous type symbol with the given member types, names, and source locations. /// Anonymous type members will be readonly by default. Writable properties are /// supported in VB and can be created by passing in <see langword="false"/> in the /// appropriate locations in <paramref name="memberIsReadOnly"/>. /// </summary> /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks> public INamedTypeSymbol CreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<bool> memberIsReadOnly, ImmutableArray<Location> memberLocations) { return CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly, memberLocations, memberNullableAnnotations: default); } protected abstract INamedTypeSymbol CommonCreateAnonymousTypeSymbol( ImmutableArray<ITypeSymbol> memberTypes, ImmutableArray<string> memberNames, ImmutableArray<Location> memberLocations, ImmutableArray<bool> memberIsReadOnly, ImmutableArray<NullableAnnotation> memberNullableAnnotations); /// <summary> /// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according /// to this compilation's programming language. /// </summary> /// <param name="source">Source type of value to be converted</param> /// <param name="destination">Destination type of value to be converted</param> /// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the /// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns> public abstract CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination); /// <summary> /// Returns true if there is an implicit (C#) or widening (VB) conversion from /// <paramref name="fromType"/> to <paramref name="toType"/>. Returns false if /// either <paramref name="fromType"/> or <paramref name="toType"/> is null, or /// if no such conversion exists. /// </summary> public bool HasImplicitConversion(ITypeSymbol? fromType, ITypeSymbol? toType) => fromType != null && toType != null && this.ClassifyCommonConversion(fromType, toType).IsImplicit; /// <summary> /// Checks if <paramref name="symbol"/> is accessible from within <paramref name="within"/>. An optional qualifier of type /// <paramref name="throughType"/> is used to resolve protected access for instance members. All symbols are /// required to be from this compilation or some assembly referenced (<see cref="References"/>) by this /// compilation. <paramref name="within"/> is required to be an <see cref="INamedTypeSymbol"/> or <see cref="IAssemblySymbol"/>. /// </summary> /// <remarks> /// <para>Submissions can reference symbols from previous submissions and their referenced assemblies, even /// though those references are missing from <see cref="References"/>. /// See https://github.com/dotnet/roslyn/issues/27356. /// This implementation works around that by permitting symbols from previous submissions as well.</para> /// <para>It is advised to avoid the use of this API within the compilers, as the compilers have additional /// requirements for access checking that are not satisfied by this implementation, including the /// avoidance of infinite recursion that could result from the use of the ISymbol APIs here, the detection /// of use-site diagnostics, and additional returned details (from the compiler's internal APIs) that are /// helpful for more precisely diagnosing reasons for accessibility failure.</para> /// </remarks> public bool IsSymbolAccessibleWithin( ISymbol symbol, ISymbol within, ITypeSymbol? throughType = null) { if (symbol is null) { throw new ArgumentNullException(nameof(symbol)); } if (within is null) { throw new ArgumentNullException(nameof(within)); } if (!(within is INamedTypeSymbol || within is IAssemblySymbol)) { throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleBadWithin, nameof(within)), nameof(within)); } checkInCompilationReferences(symbol, nameof(symbol)); checkInCompilationReferences(within, nameof(within)); if (throughType is object) { checkInCompilationReferences(throughType, nameof(throughType)); } return IsSymbolAccessibleWithinCore(symbol, within, throughType); void checkInCompilationReferences(ISymbol s, string parameterName) { if (!isContainingAssemblyInReferences(s)) { throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleWrongAssembly, parameterName), parameterName); } } bool assemblyIsInReferences(IAssemblySymbol a) { if (assemblyIsInCompilationReferences(a, this)) { return true; } if (this.IsSubmission) { // Submissions can reference symbols from previous submissions and their referenced assemblies, even // though those references are missing from this.References. We work around that by digging in // to find references of previous submissions. See https://github.com/dotnet/roslyn/issues/27356 for (Compilation? c = this.PreviousSubmission; c != null; c = c.PreviousSubmission) { if (assemblyIsInCompilationReferences(a, c)) { return true; } } } return false; } bool assemblyIsInCompilationReferences(IAssemblySymbol a, Compilation compilation) { if (a.Equals(compilation.Assembly)) { return true; } foreach (var reference in compilation.References) { if (a.Equals(compilation.GetAssemblyOrModuleSymbol(reference))) { return true; } } return false; } bool isContainingAssemblyInReferences(ISymbol s) { while (true) { switch (s.Kind) { case SymbolKind.Assembly: return assemblyIsInReferences((IAssemblySymbol)s); case SymbolKind.PointerType: s = ((IPointerTypeSymbol)s).PointedAtType; continue; case SymbolKind.ArrayType: s = ((IArrayTypeSymbol)s).ElementType; continue; case SymbolKind.Alias: s = ((IAliasSymbol)s).Target; continue; case SymbolKind.Discard: s = ((IDiscardSymbol)s).Type; continue; case SymbolKind.FunctionPointerType: var funcPtr = (IFunctionPointerTypeSymbol)s; if (!isContainingAssemblyInReferences(funcPtr.Signature.ReturnType)) { return false; } foreach (var param in funcPtr.Signature.Parameters) { if (!isContainingAssemblyInReferences(param.Type)) { return false; } } return true; case SymbolKind.DynamicType: case SymbolKind.ErrorType: case SymbolKind.Preprocessing: case SymbolKind.Namespace: // these symbols are not restricted in where they can be accessed, so unless they report // a containing assembly, we treat them as in the current assembly for access purposes return assemblyIsInReferences(s.ContainingAssembly ?? this.Assembly); default: return assemblyIsInReferences(s.ContainingAssembly); } } } } private protected abstract bool IsSymbolAccessibleWithinCore( ISymbol symbol, ISymbol within, ITypeSymbol? throughType); internal abstract IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol destination, out ConstantValue? constantValue); #endregion #region Diagnostics internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile; /// <summary> /// Gets the diagnostics produced during the parsing stage. /// </summary> public abstract ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the diagnostics produced during symbol declaration. /// </summary> public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the diagnostics produced during the analysis of method bodies and field initializers. /// </summary> public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the diagnostics for the compilation, including syntax, declaration, and /// binding. Does not include any diagnostics that might be produced during emit, see /// <see cref="EmitResult"/>. /// </summary> public abstract ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken)); internal abstract void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default); /// <summary> /// Unique metadata assembly references that are considered to be used by this compilation. /// For example, if a type declared in a referenced assembly is referenced in source code /// within this compilation, the reference is considered to be used. Etc. /// The returned set is a subset of references returned by <see cref="References"/> API. /// The result is undefined if the compilation contains errors. /// </summary> public abstract ImmutableArray<MetadataReference> GetUsedAssemblyReferences(CancellationToken cancellationToken = default(CancellationToken)); internal void EnsureCompilationEventQueueCompleted() { RoslynDebug.Assert(EventQueue != null); lock (EventQueue) { if (!EventQueue.IsCompleted) { CompleteCompilationEventQueue_NoLock(); } } } internal void CompleteCompilationEventQueue_NoLock() { RoslynDebug.Assert(EventQueue != null); // Signal the end of compilation. EventQueue.TryEnqueue(new CompilationCompletedEvent(this)); EventQueue.PromiseNotToEnqueue(); EventQueue.TryComplete(); } internal abstract CommonMessageProvider MessageProvider { get; } /// <summary> /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives. /// 'incoming' is freed. /// </summary> /// <param name="accumulator">Bag to which filtered diagnostics will be added.</param> /// <param name="incoming">Diagnostics to be filtered.</param> /// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns> internal bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, [DisallowNull] ref DiagnosticBag? incoming, CancellationToken cancellationToken) { RoslynDebug.Assert(incoming is object); bool result = FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution(), exclude: null, cancellationToken); incoming.Free(); incoming = null; return result; } /// <summary> /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives. /// </summary> /// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns> internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable<Diagnostic> incoming, HashSet<int>? exclude, CancellationToken cancellationToken) { bool hasError = false; bool reportSuppressedDiagnostics = Options.ReportSuppressedDiagnostics; foreach (Diagnostic d in incoming) { if (exclude?.Contains(d.Code) == true) { continue; } var filtered = Options.FilterDiagnostic(d, cancellationToken); if (filtered == null || (!reportSuppressedDiagnostics && filtered.IsSuppressed)) { continue; } else if (filtered.IsUnsuppressableError()) { hasError = true; } accumulator.Add(filtered); } return !hasError; } #endregion #region Resources /// <summary> /// Create a stream filled with default win32 resources. /// </summary> public Stream CreateDefaultWin32Resources(bool versionResource, bool noManifest, Stream? manifestContents, Stream? iconInIcoFormat) { //Win32 resource encodings use a lot of 16bit values. Do all of the math checked with the //expectation that integer types are well-chosen with size in mind. checked { var result = new MemoryStream(1024); //start with a null resource just as rc.exe does AppendNullResource(result); if (versionResource) AppendDefaultVersionResource(result); if (!noManifest) { if (this.Options.OutputKind.IsApplication()) { // Applications use a default manifest if one is not specified. if (manifestContents == null) { manifestContents = typeof(Compilation).GetTypeInfo().Assembly.GetManifestResourceStream("Microsoft.CodeAnalysis.Resources.default.win32manifest"); } } else { // Modules never have manifests, even if one is specified. //Debug.Assert(!this.Options.OutputKind.IsNetModule() || manifestContents == null); } if (manifestContents != null) { Win32ResourceConversions.AppendManifestToResourceStream(result, manifestContents, !this.Options.OutputKind.IsApplication()); } } if (iconInIcoFormat != null) { Win32ResourceConversions.AppendIconToResourceStream(result, iconInIcoFormat); } result.Position = 0; return result; } } internal static void AppendNullResource(Stream resourceStream) { var writer = new BinaryWriter(resourceStream); writer.Write((UInt32)0); writer.Write((UInt32)0x20); writer.Write((UInt16)0xFFFF); writer.Write((UInt16)0); writer.Write((UInt16)0xFFFF); writer.Write((UInt16)0); writer.Write((UInt32)0); //DataVersion writer.Write((UInt16)0); //MemoryFlags writer.Write((UInt16)0); //LanguageId writer.Write((UInt32)0); //Version writer.Write((UInt32)0); //Characteristics } protected abstract void AppendDefaultVersionResource(Stream resourceStream); internal enum Win32ResourceForm : byte { UNKNOWN, COFF, RES } internal static Win32ResourceForm DetectWin32ResourceForm(Stream win32Resources) { var reader = new BinaryReader(win32Resources, Encoding.Unicode); var initialPosition = win32Resources.Position; var initial32Bits = reader.ReadUInt32(); win32Resources.Position = initialPosition; //RC.EXE output starts with a resource that contains no data. if (initial32Bits == 0) return Win32ResourceForm.RES; else if ((initial32Bits & 0xFFFF0000) != 0 || (initial32Bits & 0x0000FFFF) != 0xFFFF) // See CLiteWeightStgdbRW::FindObjMetaData in peparse.cpp return Win32ResourceForm.COFF; else return Win32ResourceForm.UNKNOWN; } internal Cci.ResourceSection? MakeWin32ResourcesFromCOFF(Stream? win32Resources, DiagnosticBag diagnostics) { if (win32Resources == null) { return null; } Cci.ResourceSection resources; try { resources = COFFResourceReader.ReadWin32ResourcesFromCOFF(win32Resources); } catch (BadImageFormatException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } catch (IOException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } catch (ResourceException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } return resources; } internal List<Win32Resource>? MakeWin32ResourceList(Stream? win32Resources, DiagnosticBag diagnostics) { if (win32Resources == null) { return null; } List<RESOURCE> resources; try { resources = CvtResFile.ReadResFile(win32Resources); } catch (ResourceException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message)); return null; } if (resources == null) { return null; } var resourceList = new List<Win32Resource>(); foreach (var r in resources) { var result = new Win32Resource( data: r.data, codePage: 0, languageId: r.LanguageId, //EDMAURER converting to int from ushort. //Go to short first to avoid sign extension. id: unchecked((short)r.pstringName!.Ordinal), name: r.pstringName.theString, typeId: unchecked((short)r.pstringType!.Ordinal), typeName: r.pstringType.theString ); resourceList.Add(result); } return resourceList; } internal void SetupWin32Resources(CommonPEModuleBuilder moduleBeingBuilt, Stream? win32Resources, bool useRawWin32Resources, DiagnosticBag diagnostics) { if (win32Resources == null) return; if (useRawWin32Resources) { moduleBeingBuilt.RawWin32Resources = win32Resources; return; } Win32ResourceForm resourceForm; try { resourceForm = DetectWin32ResourceForm(win32Resources); } catch (EndOfStreamException) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat)); return; } catch (Exception ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, ex.Message)); return; } switch (resourceForm) { case Win32ResourceForm.COFF: moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics); break; case Win32ResourceForm.RES: moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics); break; default: diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat)); break; } } internal void ReportManifestResourceDuplicates( IEnumerable<ResourceDescription>? manifestResources, IEnumerable<string> addedModuleNames, IEnumerable<string> addedModuleResourceNames, DiagnosticBag diagnostics) { if (Options.OutputKind == OutputKind.NetModule && !(manifestResources != null && manifestResources.Any())) { return; } var uniqueResourceNames = new HashSet<string>(); if (manifestResources != null && manifestResources.Any()) { var uniqueFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var resource in manifestResources) { if (!uniqueResourceNames.Add(resource.ResourceName)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, resource.ResourceName)); } // file name could be null if resource is embedded var fileName = resource.FileName; if (fileName != null && !uniqueFileNames.Add(fileName)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName)); } } foreach (var fileName in addedModuleNames) { if (!uniqueFileNames.Add(fileName)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName)); } } } if (Options.OutputKind != OutputKind.NetModule) { foreach (string name in addedModuleResourceNames) { if (!uniqueResourceNames.Add(name)) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, name)); } } } } #endregion #region Emit /// <summary> /// There are two ways to sign PE files /// 1. By directly signing the <see cref="PEBuilder"/> /// 2. Write the unsigned PE to disk and use CLR COM APIs to sign. /// The preferred method is #1 as it's more efficient and more resilient (no reliance on %TEMP%). But /// we must continue to support #2 as it's the only way to do the following: /// - Access private keys stored in a key container /// - Do proper counter signature verification for AssemblySignatureKey attributes /// </summary> internal bool SignUsingBuilder => string.IsNullOrEmpty(StrongNameKeys.KeyContainer) && !StrongNameKeys.HasCounterSignature && !_features.ContainsKey("UseLegacyStrongNameProvider"); /// <summary> /// Constructs the module serialization properties out of the compilation options of this compilation. /// </summary> internal Cci.ModulePropertiesForSerialization ConstructModuleSerializationProperties( EmitOptions emitOptions, string? targetRuntimeVersion, Guid moduleVersionId = default(Guid)) { CompilationOptions compilationOptions = this.Options; Platform platform = compilationOptions.Platform; OutputKind outputKind = compilationOptions.OutputKind; if (!platform.IsValid()) { platform = Platform.AnyCpu; } if (!outputKind.IsValid()) { outputKind = OutputKind.DynamicallyLinkedLibrary; } bool requires64Bit = platform.Requires64Bit(); bool requires32Bit = platform.Requires32Bit(); ushort fileAlignment; if (emitOptions.FileAlignment == 0 || !CompilationOptions.IsValidFileAlignment(emitOptions.FileAlignment)) { fileAlignment = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultFileAlignment64Bit : Cci.ModulePropertiesForSerialization.DefaultFileAlignment32Bit; } else { fileAlignment = (ushort)emitOptions.FileAlignment; } ulong baseAddress = unchecked(emitOptions.BaseAddress + 0x8000) & (requires64Bit ? 0xffffffffffff0000 : 0x00000000ffff0000); // cover values smaller than 0x8000, overflow and default value 0): if (baseAddress == 0) { if (outputKind == OutputKind.ConsoleApplication || outputKind == OutputKind.WindowsApplication || outputKind == OutputKind.WindowsRuntimeApplication) { baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit; } else { baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress32Bit; } } ulong sizeOfHeapCommit = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit64Bit : Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit; // Dev10 always uses the default value for 32bit for sizeOfHeapReserve. // check with link -dump -headers <filename> const ulong sizeOfHeapReserve = Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit; ulong sizeOfStackReserve = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve64Bit : Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit; ulong sizeOfStackCommit = requires64Bit ? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit64Bit : Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit; SubsystemVersion subsystemVersion; if (emitOptions.SubsystemVersion.Equals(SubsystemVersion.None) || !emitOptions.SubsystemVersion.IsValid) { subsystemVersion = SubsystemVersion.Default(outputKind, platform); } else { subsystemVersion = emitOptions.SubsystemVersion; } Machine machine; switch (platform) { case Platform.Arm64: machine = Machine.Arm64; break; case Platform.Arm: machine = Machine.ArmThumb2; break; case Platform.X64: machine = Machine.Amd64; break; case Platform.Itanium: machine = Machine.IA64; break; case Platform.X86: machine = Machine.I386; break; case Platform.AnyCpu: case Platform.AnyCpu32BitPreferred: machine = Machine.Unknown; break; default: throw ExceptionUtilities.UnexpectedValue(platform); } return new Cci.ModulePropertiesForSerialization( persistentIdentifier: moduleVersionId, corFlags: GetCorHeaderFlags(machine, HasStrongName, prefers32Bit: platform == Platform.AnyCpu32BitPreferred), fileAlignment: fileAlignment, sectionAlignment: Cci.ModulePropertiesForSerialization.DefaultSectionAlignment, targetRuntimeVersion: targetRuntimeVersion, machine: machine, baseAddress: baseAddress, sizeOfHeapReserve: sizeOfHeapReserve, sizeOfHeapCommit: sizeOfHeapCommit, sizeOfStackReserve: sizeOfStackReserve, sizeOfStackCommit: sizeOfStackCommit, dllCharacteristics: GetDllCharacteristics(emitOptions.HighEntropyVirtualAddressSpace, compilationOptions.OutputKind == OutputKind.WindowsRuntimeApplication), imageCharacteristics: GetCharacteristics(outputKind, requires32Bit), subsystem: GetSubsystem(outputKind), majorSubsystemVersion: (ushort)subsystemVersion.Major, minorSubsystemVersion: (ushort)subsystemVersion.Minor, linkerMajorVersion: this.LinkerMajorVersion, linkerMinorVersion: 0); } private static CorFlags GetCorHeaderFlags(Machine machine, bool strongNameSigned, bool prefers32Bit) { CorFlags result = CorFlags.ILOnly; if (machine == Machine.I386) { result |= CorFlags.Requires32Bit; } if (strongNameSigned) { result |= CorFlags.StrongNameSigned; } if (prefers32Bit) { result |= CorFlags.Requires32Bit | CorFlags.Prefers32Bit; } return result; } internal static DllCharacteristics GetDllCharacteristics(bool enableHighEntropyVA, bool configureToExecuteInAppContainer) { var result = DllCharacteristics.DynamicBase | DllCharacteristics.NxCompatible | DllCharacteristics.NoSeh | DllCharacteristics.TerminalServerAware; if (enableHighEntropyVA) { result |= DllCharacteristics.HighEntropyVirtualAddressSpace; } if (configureToExecuteInAppContainer) { result |= DllCharacteristics.AppContainer; } return result; } private static Characteristics GetCharacteristics(OutputKind outputKind, bool requires32Bit) { var characteristics = Characteristics.ExecutableImage; if (requires32Bit) { // 32 bit machine (The standard says to always set this, the linker team says otherwise) // The loader team says that this is not used for anything in the OS. characteristics |= Characteristics.Bit32Machine; } else { // Large address aware (the standard says never to set this, the linker team says otherwise). // The loader team says that this is not overridden for managed binaries and will be respected if set. characteristics |= Characteristics.LargeAddressAware; } switch (outputKind) { case OutputKind.WindowsRuntimeMetadata: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: characteristics |= Characteristics.Dll; break; case OutputKind.ConsoleApplication: case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsApplication: break; default: throw ExceptionUtilities.UnexpectedValue(outputKind); } return characteristics; } private static Subsystem GetSubsystem(OutputKind outputKind) { switch (outputKind) { case OutputKind.ConsoleApplication: case OutputKind.DynamicallyLinkedLibrary: case OutputKind.NetModule: case OutputKind.WindowsRuntimeMetadata: return Subsystem.WindowsCui; case OutputKind.WindowsRuntimeApplication: case OutputKind.WindowsApplication: return Subsystem.WindowsGui; default: throw ExceptionUtilities.UnexpectedValue(outputKind); } } /// <summary> /// The value is not used by Windows loader, but the OS appcompat infrastructure uses it to identify apps. /// It is useful for us to have a mechanism to identify the compiler that produced the binary. /// This is the appropriate value to use for that. That is what it was invented for. /// We don't want to have the high bit set for this in case some users perform a signed comparison to /// determine if the value is less than some version. The C++ linker is at 0x0B. /// We'll start our numbering at 0x30 for C#, 0x50 for VB. /// </summary> internal abstract byte LinkerMajorVersion { get; } internal bool HasStrongName { get { return !IsDelaySigned && Options.OutputKind != OutputKind.NetModule && StrongNameKeys.CanProvideStrongName; } } internal bool IsRealSigned { get { // A module cannot be signed. The native compiler allowed one to create a netmodule with an AssemblyKeyFile // or Container attribute (or specify a key via the cmd line). When the module was linked into an assembly, // alink would sign the assembly. So rather than give an error we just don't sign when outputting a module. return !IsDelaySigned && !Options.PublicSign && Options.OutputKind != OutputKind.NetModule && StrongNameKeys.CanSign; } } /// <summary> /// Return true if the compilation contains any code or types. /// </summary> internal abstract bool HasCodeToEmit(); internal abstract bool IsDelaySigned { get; } internal abstract StrongNameKeys StrongNameKeys { get; } internal abstract CommonPEModuleBuilder? CreateModuleBuilder( EmitOptions emitOptions, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, IEnumerable<ResourceDescription>? manifestResources, CompilationTestData? testData, DiagnosticBag diagnostics, CancellationToken cancellationToken); /// <summary> /// Report declaration diagnostics and compile and synthesize method bodies. /// </summary> /// <returns>True if successful.</returns> internal abstract bool CompileMethods( CommonPEModuleBuilder moduleBuilder, bool emittingPdb, bool emitMetadataOnly, bool emitTestCoverageData, DiagnosticBag diagnostics, Predicate<ISymbolInternal>? filterOpt, CancellationToken cancellationToken); internal bool CreateDebugDocuments(DebugDocumentsBuilder documentsBuilder, IEnumerable<EmbeddedText> embeddedTexts, DiagnosticBag diagnostics) { // Check that all syntax trees are debuggable: bool allTreesDebuggable = true; foreach (var tree in CommonSyntaxTrees) { if (!string.IsNullOrEmpty(tree.FilePath) && tree.GetText().Encoding == null) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncodinglessSyntaxTree, tree.GetRoot().GetLocation())); allTreesDebuggable = false; } } if (!allTreesDebuggable) { return false; } // Add debug documents for all embedded text first. This ensures that embedding // takes priority over the syntax tree pass, which will not embed. if (!embeddedTexts.IsEmpty()) { foreach (var text in embeddedTexts) { Debug.Assert(!string.IsNullOrEmpty(text.FilePath)); string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(text.FilePath, basePath: null); var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath); if (existingDoc == null) { var document = new Cci.DebugSourceDocument( normalizedPath, DebugSourceDocumentLanguageId, () => text.GetDebugSourceInfo()); documentsBuilder.AddDebugDocument(document); } } } // Add debug documents for all trees with distinct paths. foreach (var tree in CommonSyntaxTrees) { if (!string.IsNullOrEmpty(tree.FilePath)) { // compilation does not guarantee that all trees will have distinct paths. // Do not attempt adding a document for a particular path if we already added one. string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(tree.FilePath, basePath: null); var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath); if (existingDoc == null) { documentsBuilder.AddDebugDocument(new Cci.DebugSourceDocument( normalizedPath, DebugSourceDocumentLanguageId, () => tree.GetDebugSourceInfo())); } } } // Add debug documents for all pragmas. // If there are clashes with already processed directives, report warnings. // If there are clashes with debug documents that came from actual trees, ignore the pragma. // Therefore we need to add these in a separate pass after documents for syntax trees were added. foreach (var tree in CommonSyntaxTrees) { AddDebugSourceDocumentsForChecksumDirectives(documentsBuilder, tree, diagnostics); } return true; } internal abstract Guid DebugSourceDocumentLanguageId { get; } internal abstract void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics); /// <summary> /// Update resources and generate XML documentation comments. /// </summary> /// <returns>True if successful.</returns> internal abstract bool GenerateResourcesAndDocumentationComments( CommonPEModuleBuilder moduleBeingBuilt, Stream? xmlDocumentationStream, Stream? win32ResourcesStream, bool useRawWin32Resources, string? outputNameOverride, DiagnosticBag diagnostics, CancellationToken cancellationToken); /// <summary> /// Reports all unused imports/usings so far (and thus it must be called as a last step of Emit) /// </summary> internal abstract void ReportUnusedImports( DiagnosticBag diagnostics, CancellationToken cancellationToken); internal static bool ReportUnusedImportsInTree(SyntaxTree tree) { return tree.Options.DocumentationMode != DocumentationMode.None; } /// <summary> /// Signals the event queue, if any, that we are done compiling. /// There should not be more compiling actions after this step. /// NOTE: once we signal about completion to analyzers they will cancel and thus in some cases we /// may be effectively cutting off some diagnostics. /// It is not clear if behavior is desirable. /// See: https://github.com/dotnet/roslyn/issues/11470 /// </summary> /// <param name="filterTree">What tree to complete. null means complete all trees. </param> internal abstract void CompleteTrees(SyntaxTree? filterTree); internal bool Compile( CommonPEModuleBuilder moduleBuilder, bool emittingPdb, DiagnosticBag diagnostics, Predicate<ISymbolInternal>? filterOpt, CancellationToken cancellationToken) { try { return CompileMethods( moduleBuilder, emittingPdb, emitMetadataOnly: false, emitTestCoverageData: false, diagnostics: diagnostics, filterOpt: filterOpt, cancellationToken: cancellationToken); } finally { moduleBuilder.CompilationFinished(); } } internal void EnsureAnonymousTypeTemplates(CancellationToken cancellationToken) { Debug.Assert(IsSubmission); if (this.GetSubmissionSlotIndex() >= 0 && HasCodeToEmit()) { if (!this.CommonAnonymousTypeManager.AreTemplatesSealed) { var discardedDiagnostics = DiagnosticBag.GetInstance(); var moduleBeingBuilt = this.CreateModuleBuilder( emitOptions: EmitOptions.Default, debugEntryPoint: null, manifestResources: null, sourceLinkStream: null, embeddedTexts: null, testData: null, diagnostics: discardedDiagnostics, cancellationToken: cancellationToken); if (moduleBeingBuilt != null) { Compile( moduleBeingBuilt, diagnostics: discardedDiagnostics, emittingPdb: false, filterOpt: null, cancellationToken: cancellationToken); } discardedDiagnostics.Free(); } Debug.Assert(this.CommonAnonymousTypeManager.AreTemplatesSealed); } else { this.ScriptCompilationInfo?.PreviousScriptCompilation?.EnsureAnonymousTypeTemplates(cancellationToken); } } // 1.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public EmitResult Emit( Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions options, CancellationToken cancellationToken) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint: null, sourceLinkStream: null, embeddedTexts: null, cancellationToken); } // 1.3 BACKCOMPAT OVERLOAD -- DO NOT TOUCH [EditorBrowsable(EditorBrowsableState.Never)] public EmitResult Emit( Stream peStream, Stream pdbStream, Stream xmlDocumentationStream, Stream win32Resources, IEnumerable<ResourceDescription> manifestResources, EmitOptions options, IMethodSymbol debugEntryPoint, CancellationToken cancellationToken) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream: null, embeddedTexts: null, cancellationToken); } // 2.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH public EmitResult Emit( Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, CancellationToken cancellationToken) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, metadataPEStream: null, cancellationToken: cancellationToken); } /// <summary> /// Emit the IL for the compiled source code into the specified stream. /// </summary> /// <param name="peStream">Stream to which the compilation will be written.</param> /// <param name="metadataPEStream">Stream to which the metadata-only output will be written.</param> /// <param name="pdbStream">Stream to which the compilation's debug info will be written. Null to forego PDB generation.</param> /// <param name="xmlDocumentationStream">Stream to which the compilation's XML documentation will be written. Null to forego XML generation.</param> /// <param name="win32Resources">Stream from which the compilation's Win32 resources will be read (in RES format). /// Null to indicate that there are none. The RES format begins with a null resource entry. /// Note that the caller is responsible for disposing this stream, if provided.</param> /// <param name="manifestResources">List of the compilation's managed resources. Null to indicate that there are none.</param> /// <param name="options">Emit options.</param> /// <param name="debugEntryPoint"> /// Debug entry-point of the assembly. The method token is stored in the generated PDB stream. /// /// When a program launches with a debugger attached the debugger places the first breakpoint to the start of the debug entry-point method. /// The CLR starts executing the static Main method of <see cref="CompilationOptions.MainTypeName"/> type. When the first breakpoint is hit /// the debugger steps thru the code statement by statement until user code is reached, skipping methods marked by <see cref="DebuggerHiddenAttribute"/>, /// and taking other debugging attributes into consideration. /// /// By default both entry points in an executable program (<see cref="OutputKind.ConsoleApplication"/>, <see cref="OutputKind.WindowsApplication"/>, <see cref="OutputKind.WindowsRuntimeApplication"/>) /// are the same method (Main). A non-executable program has no entry point. Runtimes that implement a custom loader may specify debug entry-point /// to force the debugger to skip over complex custom loader logic executing at the beginning of the .exe and thus improve debugging experience. /// /// Unlike ordinary entry-point which is limited to a non-generic static method of specific signature, there are no restrictions on the <paramref name="debugEntryPoint"/> /// method other than having a method body (extern, interface, or abstract methods are not allowed). /// </param> /// <param name="sourceLinkStream"> /// Stream containing information linking the compilation to a source control. /// </param> /// <param name="embeddedTexts"> /// Texts to embed in the PDB. /// Only supported when emitting Portable PDBs. /// </param> /// <param name="cancellationToken">To cancel the emit process.</param> public EmitResult Emit( Stream peStream, Stream? pdbStream = null, Stream? xmlDocumentationStream = null, Stream? win32Resources = null, IEnumerable<ResourceDescription>? manifestResources = null, EmitOptions? options = null, IMethodSymbol? debugEntryPoint = null, Stream? sourceLinkStream = null, IEnumerable<EmbeddedText>? embeddedTexts = null, Stream? metadataPEStream = null, CancellationToken cancellationToken = default(CancellationToken)) { return Emit( peStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, metadataPEStream, rebuildData: null, cancellationToken); } internal EmitResult Emit( Stream peStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions? options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, Stream? metadataPEStream, RebuildData? rebuildData, CancellationToken cancellationToken) { if (peStream == null) { throw new ArgumentNullException(nameof(peStream)); } if (!peStream.CanWrite) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(peStream)); } if (pdbStream != null) { if (options?.DebugInformationFormat == DebugInformationFormat.Embedded) { throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmbedding, nameof(pdbStream)); } if (!pdbStream.CanWrite) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(pdbStream)); } if (options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmittingMetadataOnly, nameof(pdbStream)); } } if (metadataPEStream != null && options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.MetadataPeStreamUnexpectedWhenEmittingMetadataOnly, nameof(metadataPEStream)); } if (metadataPEStream != null && options?.IncludePrivateMembers == true) { throw new ArgumentException(CodeAnalysisResources.IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream, nameof(metadataPEStream)); } if (metadataPEStream == null && options?.EmitMetadataOnly == false) { // EmitOptions used to default to IncludePrivateMembers=false, so to preserve binary compatibility we silently correct that unless emitting regular assemblies options = options.WithIncludePrivateMembers(true); } if (options?.DebugInformationFormat == DebugInformationFormat.Embedded && options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.EmbeddingPdbUnexpectedWhenEmittingMetadata, nameof(metadataPEStream)); } if (this.Options.OutputKind == OutputKind.NetModule) { if (metadataPEStream != null) { throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(metadataPEStream)); } else if (options?.EmitMetadataOnly == true) { throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(options.EmitMetadataOnly)); } } if (win32Resources != null) { if (!win32Resources.CanRead || !win32Resources.CanSeek) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(win32Resources)); } } if (sourceLinkStream != null && !sourceLinkStream.CanRead) { throw new ArgumentException(CodeAnalysisResources.StreamMustSupportRead, nameof(sourceLinkStream)); } if (embeddedTexts != null && !embeddedTexts.IsEmpty() && pdbStream == null && options?.DebugInformationFormat != DebugInformationFormat.Embedded) { throw new ArgumentException(CodeAnalysisResources.EmbeddedTextsRequirePdb, nameof(embeddedTexts)); } return Emit( peStream, metadataPEStream, pdbStream, xmlDocumentationStream, win32Resources, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, rebuildData, testData: null, cancellationToken: cancellationToken); } /// <summary> /// This overload is only intended to be directly called by tests that want to pass <paramref name="testData"/>. /// The map is used for storing a list of methods and their associated IL. /// </summary> internal EmitResult Emit( Stream peStream, Stream? metadataPEStream, Stream? pdbStream, Stream? xmlDocumentationStream, Stream? win32Resources, IEnumerable<ResourceDescription>? manifestResources, EmitOptions? options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, RebuildData? rebuildData, CompilationTestData? testData, CancellationToken cancellationToken) { options = options ?? EmitOptions.Default.WithIncludePrivateMembers(metadataPEStream == null); bool embedPdb = options.DebugInformationFormat == DebugInformationFormat.Embedded; Debug.Assert(!embedPdb || pdbStream == null); Debug.Assert(metadataPEStream == null || !options.IncludePrivateMembers); // you may not use a secondary stream and include private members together var diagnostics = DiagnosticBag.GetInstance(); var moduleBeingBuilt = CheckOptionsAndCreateModuleBuilder( diagnostics, manifestResources, options, debugEntryPoint, sourceLinkStream, embeddedTexts, testData, cancellationToken); bool success = false; if (moduleBeingBuilt != null) { try { success = CompileMethods( moduleBeingBuilt, emittingPdb: pdbStream != null || embedPdb, emitMetadataOnly: options.EmitMetadataOnly, emitTestCoverageData: options.EmitTestCoverageData, diagnostics: diagnostics, filterOpt: null, cancellationToken: cancellationToken); if (!options.EmitMetadataOnly) { // NOTE: We generate documentation even in presence of compile errors. // https://github.com/dotnet/roslyn/issues/37996 tracks revisiting this behavior. if (!GenerateResourcesAndDocumentationComments( moduleBeingBuilt, xmlDocumentationStream, win32Resources, useRawWin32Resources: rebuildData is object, options.OutputNameOverride, diagnostics, cancellationToken)) { success = false; } if (success) { ReportUnusedImports(diagnostics, cancellationToken); } } } finally { moduleBeingBuilt.CompilationFinished(); } RSAParameters? privateKeyOpt = null; if (Options.StrongNameProvider != null && SignUsingBuilder && !Options.PublicSign) { privateKeyOpt = StrongNameKeys.PrivateKey; } if (!options.EmitMetadataOnly && CommonCompiler.HasUnsuppressedErrors(diagnostics)) { success = false; } if (success) { success = SerializeToPeStream( moduleBeingBuilt, new SimpleEmitStreamProvider(peStream), (metadataPEStream != null) ? new SimpleEmitStreamProvider(metadataPEStream) : null, (pdbStream != null) ? new SimpleEmitStreamProvider(pdbStream) : null, rebuildData, testData?.SymWriterFactory, diagnostics, emitOptions: options, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken); } } return new EmitResult(success, diagnostics.ToReadOnlyAndFree()); } #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Emit the differences between the compilation and the previous generation /// for Edit and Continue. The differences are expressed as added and changed /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation /// of the current compilation is returned as an EmitBaseline for use in a /// subsequent Edit and Continue. /// </summary> [Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")] public EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection<MethodDefinitionHandle> updatedMethods, CancellationToken cancellationToken = default(CancellationToken)) { return EmitDifference(baseline, edits, s => false, metadataStream, ilStream, pdbStream, updatedMethods, cancellationToken); } /// <summary> /// Emit the differences between the compilation and the previous generation /// for Edit and Continue. The differences are expressed as added and changed /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation /// of the current compilation is returned as an EmitBaseline for use in a /// subsequent Edit and Continue. /// </summary> [Obsolete("UpdatedMethods is now part of EmitDifferenceResult, so you should use an overload that doesn't take it.")] public EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, ICollection<MethodDefinitionHandle> updatedMethods, CancellationToken cancellationToken = default(CancellationToken)) { var diff = EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, cancellationToken); foreach (var token in diff.UpdatedMethods) { updatedMethods.Add(token); } return diff; } /// <summary> /// Emit the differences between the compilation and the previous generation /// for Edit and Continue. The differences are expressed as added and changed /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation /// of the current compilation is returned as an EmitBaseline for use in a /// subsequent Edit and Continue. /// </summary> public EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CancellationToken cancellationToken = default(CancellationToken)) { if (baseline == null) { throw new ArgumentNullException(nameof(baseline)); } // TODO: check if baseline is an assembly manifest module/netmodule // Do we support EnC on netmodules? if (edits == null) { throw new ArgumentNullException(nameof(edits)); } if (isAddedSymbol == null) { throw new ArgumentNullException(nameof(isAddedSymbol)); } if (metadataStream == null) { throw new ArgumentNullException(nameof(metadataStream)); } if (ilStream == null) { throw new ArgumentNullException(nameof(ilStream)); } if (pdbStream == null) { throw new ArgumentNullException(nameof(pdbStream)); } return this.EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, testData: null, cancellationToken); } #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters internal abstract EmitDifferenceResult EmitDifference( EmitBaseline baseline, IEnumerable<SemanticEdit> edits, Func<ISymbol, bool> isAddedSymbol, Stream metadataStream, Stream ilStream, Stream pdbStream, CompilationTestData? testData, CancellationToken cancellationToken); /// <summary> /// Check compilation options and create <see cref="CommonPEModuleBuilder"/>. /// </summary> /// <returns><see cref="CommonPEModuleBuilder"/> if successful.</returns> internal CommonPEModuleBuilder? CheckOptionsAndCreateModuleBuilder( DiagnosticBag diagnostics, IEnumerable<ResourceDescription>? manifestResources, EmitOptions options, IMethodSymbol? debugEntryPoint, Stream? sourceLinkStream, IEnumerable<EmbeddedText>? embeddedTexts, CompilationTestData? testData, CancellationToken cancellationToken) { options.ValidateOptions(diagnostics, MessageProvider, Options.Deterministic); if (debugEntryPoint != null) { ValidateDebugEntryPoint(debugEntryPoint, diagnostics); } if (Options.OutputKind == OutputKind.NetModule && manifestResources != null) { foreach (ResourceDescription res in manifestResources) { if (res.FileName != null) { // Modules can have only embedded resources, not linked ones. diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceInModule, Location.None)); } } } if (CommonCompiler.HasUnsuppressableErrors(diagnostics)) { return null; } // Do not waste a slot in the submission chain for submissions that contain no executable code // (they may only contain #r directives, usings, etc.) if (IsSubmission && !HasCodeToEmit()) { // Still report diagnostics since downstream submissions will assume there are no errors. diagnostics.AddRange(this.GetDiagnostics(cancellationToken)); return null; } return this.CreateModuleBuilder( options, debugEntryPoint, sourceLinkStream, embeddedTexts, manifestResources, testData, diagnostics, cancellationToken); } internal abstract void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics); internal bool IsEmitDeterministic => this.Options.Deterministic; internal bool SerializeToPeStream( CommonPEModuleBuilder moduleBeingBuilt, EmitStreamProvider peStreamProvider, EmitStreamProvider? metadataPEStreamProvider, EmitStreamProvider? pdbStreamProvider, RebuildData? rebuildData, Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory, DiagnosticBag diagnostics, EmitOptions emitOptions, RSAParameters? privateKeyOpt, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); Cci.PdbWriter? nativePdbWriter = null; DiagnosticBag? metadataDiagnostics = null; DiagnosticBag? pdbBag = null; bool deterministic = IsEmitDeterministic; // PDB Stream provider should not be given if PDB is to be embedded into the PE file: Debug.Assert(moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Embedded || pdbStreamProvider == null); string? pePdbFilePath = emitOptions.PdbFilePath; if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded || pdbStreamProvider != null) { pePdbFilePath = pePdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"); } else { pePdbFilePath = null; } if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded && !RoslynString.IsNullOrEmpty(pePdbFilePath)) { pePdbFilePath = PathUtilities.GetFileName(pePdbFilePath); } EmitStream? emitPeStream = null; EmitStream? emitMetadataStream = null; try { var signKind = IsRealSigned ? (SignUsingBuilder ? EmitStreamSignKind.SignedWithBuilder : EmitStreamSignKind.SignedWithFile) : EmitStreamSignKind.None; emitPeStream = new EmitStream(peStreamProvider, signKind, Options.StrongNameProvider); emitMetadataStream = metadataPEStreamProvider == null ? null : new EmitStream(metadataPEStreamProvider, signKind, Options.StrongNameProvider); metadataDiagnostics = DiagnosticBag.GetInstance(); if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Pdb && pdbStreamProvider != null) { // The algorithm must be specified for deterministic builds (checked earlier). Debug.Assert(!deterministic || moduleBeingBuilt.PdbChecksumAlgorithm.Name != null); // The calls ISymUnmanagedWriter2.GetDebugInfo require a file name in order to succeed. This is // frequently used during PDB writing. Ensure a name is provided here in the case we were given // only a Stream value. nativePdbWriter = new Cci.PdbWriter(pePdbFilePath, testSymWriterFactory, deterministic ? moduleBeingBuilt.PdbChecksumAlgorithm : default); } Func<Stream?>? getPortablePdbStream = moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.PortablePdb || pdbStreamProvider == null ? null : (Func<Stream?>)(() => ConditionalGetOrCreateStream(pdbStreamProvider, metadataDiagnostics)); try { if (SerializePeToStream( moduleBeingBuilt, metadataDiagnostics, MessageProvider, emitPeStream.GetCreateStreamFunc(metadataDiagnostics), emitMetadataStream?.GetCreateStreamFunc(metadataDiagnostics), getPortablePdbStream, nativePdbWriter, pePdbFilePath, rebuildData, emitOptions.EmitMetadataOnly, emitOptions.IncludePrivateMembers, deterministic, emitOptions.EmitTestCoverageData, privateKeyOpt, cancellationToken)) { if (nativePdbWriter != null) { var nativePdbStream = pdbStreamProvider!.GetOrCreateStream(metadataDiagnostics); Debug.Assert(nativePdbStream != null || metadataDiagnostics.HasAnyErrors()); if (nativePdbStream != null) { nativePdbWriter.WriteTo(nativePdbStream); } } } } catch (SymUnmanagedWriterException ex) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message)); return false; } catch (Cci.PeWritingException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? "")); return false; } catch (ResourceException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_CantReadResource, Location.None, e.Message, e.InnerException?.Message ?? "")); return false; } catch (PermissionSetFileReadException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message)); return false; } // translate metadata errors. if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics, cancellationToken)) { return false; } return emitPeStream.Complete(StrongNameKeys, MessageProvider, diagnostics) && (emitMetadataStream?.Complete(StrongNameKeys, MessageProvider, diagnostics) ?? true); } finally { nativePdbWriter?.Dispose(); emitPeStream?.Close(); emitMetadataStream?.Close(); pdbBag?.Free(); metadataDiagnostics?.Free(); } } private static Stream? ConditionalGetOrCreateStream(EmitStreamProvider metadataPEStreamProvider, DiagnosticBag metadataDiagnostics) { if (metadataDiagnostics.HasAnyErrors()) { return null; } var auxStream = metadataPEStreamProvider.GetOrCreateStream(metadataDiagnostics); Debug.Assert(auxStream != null || metadataDiagnostics.HasAnyErrors()); return auxStream; } internal static bool SerializePeToStream( CommonPEModuleBuilder moduleBeingBuilt, DiagnosticBag metadataDiagnostics, CommonMessageProvider messageProvider, Func<Stream?> getPeStream, Func<Stream?>? getMetadataPeStreamOpt, Func<Stream?>? getPortablePdbStreamOpt, Cci.PdbWriter? nativePdbWriterOpt, string? pdbPathOpt, RebuildData? rebuildData, bool metadataOnly, bool includePrivateMembers, bool isDeterministic, bool emitTestCoverageData, RSAParameters? privateKeyOpt, CancellationToken cancellationToken) { bool emitSecondaryAssembly = getMetadataPeStreamOpt != null; bool includePrivateMembersOnPrimaryOutput = metadataOnly ? includePrivateMembers : true; bool deterministicPrimaryOutput = (metadataOnly && !includePrivateMembers) || isDeterministic; if (!Cci.PeWriter.WritePeToStream( new EmitContext(moduleBeingBuilt, metadataDiagnostics, metadataOnly, includePrivateMembersOnPrimaryOutput, rebuildData: rebuildData), messageProvider, getPeStream, getPortablePdbStreamOpt, nativePdbWriterOpt, pdbPathOpt, metadataOnly, deterministicPrimaryOutput, emitTestCoverageData, privateKeyOpt, cancellationToken)) { return false; } // produce the secondary output (ref assembly) if needed if (emitSecondaryAssembly) { Debug.Assert(!metadataOnly); Debug.Assert(!includePrivateMembers); if (!Cci.PeWriter.WritePeToStream( new EmitContext(moduleBeingBuilt, syntaxNode: null, metadataDiagnostics, metadataOnly: true, includePrivateMembers: false), messageProvider, getMetadataPeStreamOpt, getPortablePdbStreamOpt: null, nativePdbWriterOpt: null, pdbPathOpt: null, metadataOnly: true, isDeterministic: true, emitTestCoverageData: false, privateKeyOpt: privateKeyOpt, cancellationToken: cancellationToken)) { return false; } } return true; } internal EmitBaseline? SerializeToDeltaStreams( CommonPEModuleBuilder moduleBeingBuilt, EmitBaseline baseline, DefinitionMap definitionMap, SymbolChanges changes, Stream metadataStream, Stream ilStream, Stream pdbStream, ArrayBuilder<MethodDefinitionHandle> updatedMethods, ArrayBuilder<TypeDefinitionHandle> changedTypes, DiagnosticBag diagnostics, Func<ISymWriterMetadataProvider, SymUnmanagedWriter>? testSymWriterFactory, string? pdbFilePath, CancellationToken cancellationToken) { var nativePdbWriter = (moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Pdb) ? null : new Cci.PdbWriter( pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"), testSymWriterFactory, hashAlgorithmNameOpt: default); using (nativePdbWriter) { var context = new EmitContext(moduleBeingBuilt, diagnostics, metadataOnly: false, includePrivateMembers: true); var encId = Guid.NewGuid(); try { var writer = new DeltaMetadataWriter( context, MessageProvider, baseline, encId, definitionMap, changes, cancellationToken); writer.WriteMetadataAndIL( nativePdbWriter, metadataStream, ilStream, (nativePdbWriter == null) ? pdbStream : null, out MetadataSizes metadataSizes); writer.GetUpdatedMethodTokens(updatedMethods); writer.GetChangedTypeTokens(changedTypes); nativePdbWriter?.WriteTo(pdbStream); return diagnostics.HasAnyErrors() ? null : writer.GetDelta(this, encId, metadataSizes); } catch (SymUnmanagedWriterException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, e.Message)); return null; } catch (Cci.PeWritingException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException?.ToString() ?? "")); return null; } catch (PermissionSetFileReadException e) { diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message)); return null; } } } internal string? Feature(string p) { string? v; return _features.TryGetValue(p, out v) ? v : null; } #endregion private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts>? _lazyTreeToUsedImportDirectivesMap; private static readonly Func<SyntaxTree, SmallConcurrentSetOfInts> s_createSetCallback = t => new SmallConcurrentSetOfInts(); private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts> TreeToUsedImportDirectivesMap { get { return RoslynLazyInitializer.EnsureInitialized(ref _lazyTreeToUsedImportDirectivesMap); } } internal void MarkImportDirectiveAsUsed(SyntaxReference node) { MarkImportDirectiveAsUsed(node.SyntaxTree, node.Span.Start); } internal void MarkImportDirectiveAsUsed(SyntaxTree? syntaxTree, int position) { // Optimization: Don't initialize TreeToUsedImportDirectivesMap in submissions. if (!IsSubmission && syntaxTree != null) { var set = TreeToUsedImportDirectivesMap.GetOrAdd(syntaxTree, s_createSetCallback); set.Add(position); } } internal bool IsImportDirectiveUsed(SyntaxTree syntaxTree, int position) { if (IsSubmission) { // Since usings apply to subsequent submissions, we have to assume they are used. return true; } SmallConcurrentSetOfInts? usedImports; return syntaxTree != null && TreeToUsedImportDirectivesMap.TryGetValue(syntaxTree, out usedImports) && usedImports.Contains(position); } /// <summary> /// The compiler needs to define an ordering among different partial class in different syntax trees /// in some cases, because emit order for fields in structures, for example, is semantically important. /// This function defines an ordering among syntax trees in this compilation. /// </summary> internal int CompareSyntaxTreeOrdering(SyntaxTree tree1, SyntaxTree tree2) { if (tree1 == tree2) { return 0; } Debug.Assert(this.ContainsSyntaxTree(tree1)); Debug.Assert(this.ContainsSyntaxTree(tree2)); return this.GetSyntaxTreeOrdinal(tree1) - this.GetSyntaxTreeOrdinal(tree2); } internal abstract int GetSyntaxTreeOrdinal(SyntaxTree tree); /// <summary> /// Compare two source locations, using their containing trees, and then by Span.First within a tree. /// Can be used to get a total ordering on declarations, for example. /// </summary> internal abstract int CompareSourceLocations(Location loc1, Location loc2); /// <summary> /// Compare two source locations, using their containing trees, and then by Span.First within a tree. /// Can be used to get a total ordering on declarations, for example. /// </summary> internal abstract int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2); /// <summary> /// Compare two source locations, using their containing trees, and then by Span.First within a tree. /// Can be used to get a total ordering on declarations, for example. /// </summary> internal abstract int CompareSourceLocations(SyntaxNode loc1, SyntaxNode loc2); /// <summary> /// Return the lexically first of two locations. /// </summary> internal TLocation FirstSourceLocation<TLocation>(TLocation first, TLocation second) where TLocation : Location { if (CompareSourceLocations(first, second) <= 0) { return first; } else { return second; } } /// <summary> /// Return the lexically first of multiple locations. /// </summary> internal TLocation? FirstSourceLocation<TLocation>(ImmutableArray<TLocation> locations) where TLocation : Location { if (locations.IsEmpty) { return null; } var result = locations[0]; for (int i = 1; i < locations.Length; i++) { result = FirstSourceLocation(result, locations[i]); } return result; } #region Logging Helpers // Following helpers are used when logging ETW events. These helpers are invoked only if we are running // under an ETW listener that has requested 'verbose' logging. In other words, these helpers will never // be invoked in the 'normal' case (i.e. when the code is running on user's machine and no ETW listener // is involved). // Note: Most of the below helpers are unused at the moment - but we would like to keep them around in // case we decide we need more verbose logging in certain cases for debugging. internal string GetMessage(CompilationStage stage) { return string.Format("{0} ({1})", this.AssemblyName, stage.ToString()); } internal string GetMessage(ITypeSymbol source, ITypeSymbol destination) { if (source == null || destination == null) return this.AssemblyName ?? ""; return string.Format("{0}: {1} {2} -> {3} {4}", this.AssemblyName, source.TypeKind.ToString(), source.Name, destination.TypeKind.ToString(), destination.Name); } #endregion #region Declaration Name Queries /// <summary> /// Return true if there is a source declaration symbol name that meets given predicate. /// </summary> public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return source declaration symbols whose name meets given predicate. /// </summary> public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); #pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters /// <summary> /// Return true if there is a source declaration symbol name that matches the provided name. /// This may be faster than <see cref="ContainsSymbolsWithName(Func{string, bool}, /// SymbolFilter, CancellationToken)"/> when predicate is just a simple string check. /// <paramref name="name"/> is case sensitive or not depending on the target language. /// </summary> public abstract bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Return source declaration symbols whose name matches the provided name. This may be /// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter, /// CancellationToken)"/> when predicate is just a simple string check. <paramref /// name="name"/> is case sensitive or not depending on the target language. /// </summary> public abstract IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken)); #pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters #endregion internal void MakeMemberMissing(WellKnownMember member) { MakeMemberMissing((int)member); } internal void MakeMemberMissing(SpecialMember member) { MakeMemberMissing(-(int)member - 1); } internal bool IsMemberMissing(WellKnownMember member) { return IsMemberMissing((int)member); } internal bool IsMemberMissing(SpecialMember member) { return IsMemberMissing(-(int)member - 1); } private void MakeMemberMissing(int member) { if (_lazyMakeMemberMissingMap == null) { _lazyMakeMemberMissingMap = new SmallDictionary<int, bool>(); } _lazyMakeMemberMissingMap[member] = true; } private bool IsMemberMissing(int member) { return _lazyMakeMemberMissingMap != null && _lazyMakeMemberMissingMap.ContainsKey(member); } internal void MakeTypeMissing(SpecialType type) { MakeTypeMissing((int)type); } internal void MakeTypeMissing(WellKnownType type) { MakeTypeMissing((int)type); } private void MakeTypeMissing(int type) { if (_lazyMakeWellKnownTypeMissingMap == null) { _lazyMakeWellKnownTypeMissingMap = new SmallDictionary<int, bool>(); } _lazyMakeWellKnownTypeMissingMap[(int)type] = true; } internal bool IsTypeMissing(SpecialType type) { return IsTypeMissing((int)type); } internal bool IsTypeMissing(WellKnownType type) { return IsTypeMissing((int)type); } private bool IsTypeMissing(int type) { return _lazyMakeWellKnownTypeMissingMap != null && _lazyMakeWellKnownTypeMissingMap.ContainsKey((int)type); } /// <summary> /// Given a <see cref="Diagnostic"/> reporting unreferenced <see cref="AssemblyIdentity"/>s, returns /// the actual <see cref="AssemblyIdentity"/> instances that were not referenced. /// </summary> public ImmutableArray<AssemblyIdentity> GetUnreferencedAssemblyIdentities(Diagnostic diagnostic) { if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } if (!IsUnreferencedAssemblyIdentityDiagnosticCode(diagnostic.Code)) { return ImmutableArray<AssemblyIdentity>.Empty; } var builder = ArrayBuilder<AssemblyIdentity>.GetInstance(); foreach (var argument in diagnostic.Arguments) { if (argument is AssemblyIdentity id) { builder.Add(id); } } return builder.ToImmutableAndFree(); } internal abstract bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code); /// <summary> /// Returns the required language version found in a <see cref="Diagnostic"/>, if any is found. /// Returns null if none is found. /// </summary> public static string? GetRequiredLanguageVersion(Diagnostic diagnostic) { if (diagnostic == null) { throw new ArgumentNullException(nameof(diagnostic)); } bool found = false; string? foundVersion = null; if (diagnostic.Arguments != null) { foreach (var argument in diagnostic.Arguments) { if (argument is RequiredLanguageVersion versionDiagnostic) { Debug.Assert(!found); // only one required language version in a given diagnostic found = true; foundVersion = versionDiagnostic.ToString(); } } } return foundVersion; } } }
1
dotnet/roslyn
56,218
Eliminate 75GB allocations during binding in a performance trace
Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
sharwell
"2021-09-07T16:51:03Z"
"2021-09-09T22:25:38Z"
e3e8c6e5196d73d1b7582d40a3c48a22c68e6441
ba2203796b7906d6f53b53bc6fa93f1708e11944
Eliminate 75GB allocations during binding in a performance trace. Fixes two of the most expensive allocation paths shown in the performance trace attached to [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013). Fixes [AB#1389013](https://devdiv.visualstudio.com/0bdbc590-a062-4c3f-b0f6-9383f67865ee/_workitems/edit/1389013)
./src/Compilers/Core/Portable/Syntax/SyntaxNodeLocationComparer.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.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { internal class SyntaxNodeLocationComparer : IComparer<SyntaxNode> { private readonly Compilation _compilation; public SyntaxNodeLocationComparer(Compilation compilation) { _compilation = compilation; } public int Compare(SyntaxNode? x, SyntaxNode? y) { if (x is null) { if (y is null) { return 0; } return -1; } else if (y is null) { return 1; } else { return _compilation.CompareSourceLocations(x.GetLocation(), y.GetLocation()); } } } }
// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis { internal class SyntaxNodeLocationComparer : IComparer<SyntaxNode> { private readonly Compilation _compilation; public SyntaxNodeLocationComparer(Compilation compilation) { _compilation = compilation; } public int Compare(SyntaxNode? x, SyntaxNode? y) { if (x is null) { if (y is null) { return 0; } return -1; } else if (y is null) { return 1; } else { return _compilation.CompareSourceLocations(x, y); } } } }
1